<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Spring源码系列-第5章-容器刷新流程 | 风祈的时光录</title><meta name="keywords" content="Spring，框架，spring源码"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="容器刷新全流程">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring源码系列-第5章-容器刷新流程">
<meta property="og:url" content="https://imlql.cn/post/a1b8c236.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="容器刷新全流程">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png">
<meta property="article:published_time" content="2022-02-13T10:01:02.000Z">
<meta property="article:modified_time" content="2022-07-24T11:22:15.041Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="Spring源码">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/a1b8c236"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring源码系列-第5章-容器刷新流程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:22:15'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://npm.elemecdn.com/lql_static@latest/logo/spring.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring源码系列-第5章-容器刷新流程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-02-13T10:01:02.000Z" title="发表于 2022-02-13 18:01:02">2022-02-13</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:22:15.041Z" title="更新于 2022-07-24 19:22:15">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/%E6%BA%90%E7%A0%81V1/">源码V1</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">8.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>41分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="第5章-容器刷新流程"><a href="#第5章-容器刷新流程" class="headerlink" title="第5章-容器刷新流程"></a>第5章-容器刷新流程</h1><h2 id="流程图-容器刷新"><a href="#流程图-容器刷新" class="headerlink" title="流程图-容器刷新"></a>流程图-容器刷新</h2><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.7/spring-sourcecode-v1/flow_chart/%E5%AE%B9%E5%99%A8%E5%88%B7%E6%96%B0%E6%B5%81%E7%A8%8B.jpg">

<h2 id="容器创建"><a href="#容器创建" class="headerlink" title="容器创建"></a>容器创建</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AnnotationMainTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">      ApplicationContext applicationContext =</span><br><span class="line">            <span class="keyword">new</span> AnnotationConfigApplicationContext(MainConfig.class);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>



<h3 id="AnnotationConfigApplicationContext有参构造"><a href="#AnnotationConfigApplicationContext有参构造" class="headerlink" title="AnnotationConfigApplicationContext有参构造"></a>AnnotationConfigApplicationContext有参构造</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AnnotationConfigApplicationContext</span><span class="params">(Class&lt;?&gt;... componentClasses)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">this</span>();</span><br><span class="line">   register(componentClasses);</span><br><span class="line">   refresh(); <span class="comment">//容器完整刷新（创建出所有组件，组织好所有功能）</span></span><br><span class="line">&#125;	</span><br></pre></td></tr></table></figure>

<h4 id="AnnotationConfigApplicationContext-this-无参构造"><a href="#AnnotationConfigApplicationContext-this-无参构造" class="headerlink" title="AnnotationConfigApplicationContext#this()无参构造"></a>AnnotationConfigApplicationContext#this()无参构造</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 上面的this()就是调用的这里</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AnnotationConfigApplicationContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    StartupStep createAnnotatedBeanDefReader = <span class="keyword">this</span>.getApplicationStartup().start(<span class="string">&quot;spring.context.annotated-bean-reader.create&quot;</span>);</span><br><span class="line">    <span class="keyword">this</span>.reader = <span class="keyword">new</span> AnnotatedBeanDefinitionReader(<span class="keyword">this</span>);</span><br><span class="line">    createAnnotatedBeanDefReader.end();</span><br><span class="line">    <span class="keyword">this</span>.scanner = <span class="keyword">new</span> ClassPathBeanDefinitionScanner(<span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="AnnotatedBeanDefinitionReader有参构造"><a href="#AnnotatedBeanDefinitionReader有参构造" class="headerlink" title="AnnotatedBeanDefinitionReader有参构造"></a>AnnotatedBeanDefinitionReader有参构造</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">AnnotatedBeanDefinitionReader</span><span class="params">(BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>(registry, getOrCreateEnvironment(registry));</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AnnotatedBeanDefinitionReader</span><span class="params">(BeanDefinitionRegistry registry, Environment environment)</span> </span>&#123;</span><br><span class="line">	Assert.notNull(registry, <span class="string">&quot;BeanDefinitionRegistry must not be null&quot;</span>);</span><br><span class="line">	Assert.notNull(environment, <span class="string">&quot;Environment must not be null&quot;</span>);</span><br><span class="line">	<span class="keyword">this</span>.registry = registry;</span><br><span class="line">	<span class="keyword">this</span>.conditionEvaluator = <span class="keyword">new</span> ConditionEvaluator(registry, environment, <span class="keyword">null</span>);</span><br><span class="line">	AnnotationConfigUtils.registerAnnotationConfigProcessors(<span class="keyword">this</span>.registry);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="AnnotationConfigUtils-registerAnnotationConfigProcessors-注册Spring内部几个核心组件"><a href="#AnnotationConfigUtils-registerAnnotationConfigProcessors-注册Spring内部几个核心组件" class="headerlink" title="AnnotationConfigUtils#registerAnnotationConfigProcessors()注册Spring内部几个核心组件"></a>AnnotationConfigUtils#registerAnnotationConfigProcessors()注册Spring内部几个核心组件</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The bean name of the internally managed Configuration annotation processor.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =</span><br><span class="line">		<span class="string">&quot;org.springframework.context.annotation.internalConfigurationAnnotationProcessor&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The bean name of the internally managed BeanNameGenerator for use when processing</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> Configuration&#125; classes. Set by &#123;<span class="doctag">@link</span> AnnotationConfigApplicationContext&#125;</span></span><br><span class="line"><span class="comment"> * and &#123;<span class="doctag">@code</span> AnnotationConfigWebApplicationContext&#125; during bootstrap in order to make</span></span><br><span class="line"><span class="comment"> * any custom name generation strategy available to the underlying</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> ConfigurationClassPostProcessor&#125;.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 3.1.1</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String CONFIGURATION_BEAN_NAME_GENERATOR =</span><br><span class="line">		<span class="string">&quot;org.springframework.context.annotation.internalConfigurationBeanNameGenerator&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The bean name of the internally managed Autowired annotation processor.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME =</span><br><span class="line">		<span class="string">&quot;org.springframework.context.annotation.internalAutowiredAnnotationProcessor&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The bean name of the internally managed Required annotation processor.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@deprecated</span> as of 5.1, since no Required processor is registered by default anymore</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Deprecated</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME =</span><br><span class="line">		<span class="string">&quot;org.springframework.context.annotation.internalRequiredAnnotationProcessor&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The bean name of the internally managed JSR-250 annotation processor.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String COMMON_ANNOTATION_PROCESSOR_BEAN_NAME =</span><br><span class="line">		<span class="string">&quot;org.springframework.context.annotation.internalCommonAnnotationProcessor&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The bean name of the internally managed JPA annotation processor.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME =</span><br><span class="line">		<span class="string">&quot;org.springframework.context.annotation.internalPersistenceAnnotationProcessor&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME =</span><br><span class="line">		<span class="string">&quot;org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The bean name of the internally managed <span class="doctag">@EventListener</span> annotation processor.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String EVENT_LISTENER_PROCESSOR_BEAN_NAME =</span><br><span class="line">		<span class="string">&quot;org.springframework.context.event.internalEventListenerProcessor&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The bean name of the internally managed EventListenerFactory.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String EVENT_LISTENER_FACTORY_BEAN_NAME =</span><br><span class="line">		<span class="string">&quot;org.springframework.context.event.internalEventListenerFactory&quot;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">registerAnnotationConfigProcessors</span><span class="params">(BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">      registerAnnotationConfigProcessors(registry, <span class="keyword">null</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Set&lt;BeanDefinitionHolder&gt; <span class="title">registerAnnotationConfigProcessors</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">		BeanDefinitionRegistry registry, <span class="meta">@Nullable</span> Object source)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);</span><br><span class="line">	<span class="keyword">if</span> (beanFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">if</span> (!(beanFactory.getDependencyComparator() <span class="keyword">instanceof</span> AnnotationAwareOrderComparator)) &#123;</span><br><span class="line">			beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (!(beanFactory.getAutowireCandidateResolver() <span class="keyword">instanceof</span> ContextAnnotationAutowireCandidateResolver)) &#123;</span><br><span class="line">			beanFactory.setAutowireCandidateResolver(<span class="keyword">new</span> ContextAnnotationAutowireCandidateResolver());</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">       <span class="comment">//下面是注册Spring底层的核心组件，主要是就是Spring自己的BeanPostproPostProcessor或者BeanFactoryPostProcessor</span></span><br><span class="line">	Set&lt;BeanDefinitionHolder&gt; beanDefs = <span class="keyword">new</span> LinkedHashSet&lt;&gt;(<span class="number">8</span>);</span><br><span class="line">	<span class="comment">//注册底层的  配置文件处理器</span></span><br><span class="line">	<span class="keyword">if</span> (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) &#123;</span><br><span class="line">		RootBeanDefinition def = <span class="keyword">new</span> RootBeanDefinition(ConfigurationClassPostProcessor.class);</span><br><span class="line">		def.setSource(source);</span><br><span class="line">		beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));</span><br><span class="line">	&#125;</span><br><span class="line">       <span class="comment">//注册底层的自动装配处理器</span></span><br><span class="line">	<span class="keyword">if</span> (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) &#123;</span><br><span class="line">		RootBeanDefinition def = <span class="keyword">new</span> RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);</span><br><span class="line">		def.setSource(source);</span><br><span class="line">		beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));</span><br><span class="line">	&#125;</span><br><span class="line">       <span class="comment">//注册支持JSR-250的处理</span></span><br><span class="line">	<span class="comment">// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.</span></span><br><span class="line">	<span class="keyword">if</span> (jsr250Present &amp;&amp; !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) &#123;</span><br><span class="line">		RootBeanDefinition def = <span class="keyword">new</span> RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);</span><br><span class="line">		def.setSource(source);</span><br><span class="line">		beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.</span></span><br><span class="line">	<span class="keyword">if</span> (jpaPresent &amp;&amp; !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) &#123;</span><br><span class="line">		RootBeanDefinition def = <span class="keyword">new</span> RootBeanDefinition();</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,</span><br><span class="line">					AnnotationConfigUtils.class.getClassLoader()));</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (ClassNotFoundException ex) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(</span><br><span class="line">					<span class="string">&quot;Cannot load optional framework class: &quot;</span> + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);</span><br><span class="line">		&#125;</span><br><span class="line">		def.setSource(source);</span><br><span class="line">		beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) &#123;</span><br><span class="line">		RootBeanDefinition def = <span class="keyword">new</span> RootBeanDefinition(EventListenerMethodProcessor.class);</span><br><span class="line">		def.setSource(source);</span><br><span class="line">		beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) &#123;</span><br><span class="line">		RootBeanDefinition def = <span class="keyword">new</span> RootBeanDefinition(DefaultEventListenerFactory.class);</span><br><span class="line">		def.setSource(source);</span><br><span class="line">		beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> beanDefs;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>上面的方法走完，我们可以看看到主要是下面4个后置处理器</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211008212541000.png"/>

<h5 id="RootBeanDefinition"><a href="#RootBeanDefinition" class="headerlink" title="RootBeanDefinition"></a>RootBeanDefinition</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">RootBeanDefinition</span><span class="params">(<span class="meta">@Nullable</span> Class&lt;?&gt; beanClass)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">super</span>();</span><br><span class="line">   setBeanClass(beanClass);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="AbstractBeanDefinition"><a href="#AbstractBeanDefinition" class="headerlink" title="AbstractBeanDefinition"></a>AbstractBeanDefinition</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="title">AbstractBeanDefinition</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   <span class="keyword">this</span>(<span class="keyword">null</span>, <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="ClassPathBeanDefinitionScanner"><a href="#ClassPathBeanDefinitionScanner" class="headerlink" title="ClassPathBeanDefinitionScanner"></a>ClassPathBeanDefinitionScanner</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ClassPathBeanDefinitionScanner</span><span class="params">(BeanDefinitionRegistry registry, <span class="keyword">boolean</span> useDefaultFilters,</span></span></span><br><span class="line"><span class="function"><span class="params">      Environment environment, <span class="meta">@Nullable</span> ResourceLoader resourceLoader)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   Assert.notNull(registry, <span class="string">&quot;BeanDefinitionRegistry must not be null&quot;</span>);</span><br><span class="line">   <span class="keyword">this</span>.registry = registry;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (useDefaultFilters) &#123;</span><br><span class="line">      registerDefaultFilters();</span><br><span class="line">   &#125;</span><br><span class="line">   setEnvironment(environment); <span class="comment">//准备环境</span></span><br><span class="line">   setResourceLoader(resourceLoader);<span class="comment">//准备资源加载器</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="AnnotationConfigApplicationContext-register"><a href="#AnnotationConfigApplicationContext-register" class="headerlink" title="AnnotationConfigApplicationContext#register()"></a>AnnotationConfigApplicationContext#register()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">register</span><span class="params">(Class&lt;?&gt;... componentClasses)</span> </span>&#123;</span><br><span class="line">   <span class="comment">//componentClasses就是咱们的配置类</span></span><br><span class="line">   Assert.notEmpty(componentClasses, <span class="string">&quot;At least one component class must be specified&quot;</span>);</span><br><span class="line">   StartupStep registerComponentClass = <span class="keyword">this</span>.getApplicationStartup().start(<span class="string">&quot;spring.context.component-classes.register&quot;</span>)</span><br><span class="line">         .tag(<span class="string">&quot;classes&quot;</span>, () -&gt; Arrays.toString(componentClasses));</span><br><span class="line">   <span class="keyword">this</span>.reader.register(componentClasses);</span><br><span class="line">   registerComponentClass.end();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="AnnotatedBeanDefinitionReader-register-注册主配置类BeanDefinition"><a href="#AnnotatedBeanDefinitionReader-register-注册主配置类BeanDefinition" class="headerlink" title="AnnotatedBeanDefinitionReader#register()注册主配置类BeanDefinition"></a>AnnotatedBeanDefinitionReader#register()注册主配置类BeanDefinition</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">register</span><span class="params">(Class&lt;?&gt;... componentClasses)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">for</span> (Class&lt;?&gt; componentClass : componentClasses) &#123;</span><br><span class="line">         registerBean(componentClass);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBean</span><span class="params">(Class&lt;?&gt; beanClass)</span> </span>&#123;</span><br><span class="line">	doRegisterBean(beanClass, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">doRegisterBean</span><span class="params">(Class&lt;T&gt; beanClass, <span class="meta">@Nullable</span> String name,</span></span></span><br><span class="line"><span class="function"><span class="params">		<span class="meta">@Nullable</span> Class&lt;? extends Annotation&gt;[] qualifiers, <span class="meta">@Nullable</span> Supplier&lt;T&gt; supplier,</span></span></span><br><span class="line"><span class="function"><span class="params">		<span class="meta">@Nullable</span> BeanDefinitionCustomizer[] customizers)</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">       <span class="comment">// 主配置类也被封装成一个Bean定义信息了</span></span><br><span class="line">	AnnotatedGenericBeanDefinition abd = <span class="keyword">new</span> AnnotatedGenericBeanDefinition(beanClass);</span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.conditionEvaluator.shouldSkip(abd.getMetadata())) &#123;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	abd.setInstanceSupplier(supplier);</span><br><span class="line">	ScopeMetadata scopeMetadata = <span class="keyword">this</span>.scopeMetadataResolver.resolveScopeMetadata(abd);</span><br><span class="line">	abd.setScope(scopeMetadata.getScopeName());</span><br><span class="line">	String beanName = (name != <span class="keyword">null</span> ? name : <span class="keyword">this</span>.beanNameGenerator.generateBeanName(abd, <span class="keyword">this</span>.registry));</span><br><span class="line">	<span class="comment">//完善主配置类的BeanDefinition</span></span><br><span class="line">	AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);</span><br><span class="line">	<span class="keyword">if</span> (qualifiers != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">for</span> (Class&lt;? extends Annotation&gt; qualifier : qualifiers) &#123;</span><br><span class="line">			<span class="keyword">if</span> (Primary.class == qualifier) &#123;</span><br><span class="line">				abd.setPrimary(<span class="keyword">true</span>);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span> (Lazy.class == qualifier) &#123;</span><br><span class="line">				abd.setLazyInit(<span class="keyword">true</span>);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> &#123;</span><br><span class="line">				abd.addQualifier(<span class="keyword">new</span> AutowireCandidateQualifier(qualifier));</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (customizers != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">for</span> (BeanDefinitionCustomizer customizer : customizers) &#123;</span><br><span class="line">			customizer.customize(abd);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	BeanDefinitionHolder definitionHolder = <span class="keyword">new</span> BeanDefinitionHolder(abd, beanName);</span><br><span class="line">	definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, <span class="keyword">this</span>.registry);</span><br><span class="line">	BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, <span class="keyword">this</span>.registry);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h5 id="AnnotationConfigUtils-processCommonDefinitionAnnotations-感知-Lazy，-Primary等注解"><a href="#AnnotationConfigUtils-processCommonDefinitionAnnotations-感知-Lazy，-Primary等注解" class="headerlink" title="AnnotationConfigUtils#processCommonDefinitionAnnotations()感知@Lazy，@Primary等注解"></a>AnnotationConfigUtils#processCommonDefinitionAnnotations()感知@Lazy，@Primary等注解</h5><p>这里传进来的是主配置类，解析的就是主配置类的注解，其它的Bean这里还没有解析@Lazy，@Primary这些注解</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">processCommonDefinitionAnnotations</span><span class="params">(AnnotatedBeanDefinition abd)</span> </span>&#123;</span><br><span class="line">   processCommonDefinitionAnnotations(abd, abd.getMetadata());</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//解读所有Bean定义信息需要感知的注解</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">processCommonDefinitionAnnotations</span><span class="params">(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata)</span> </span>&#123;</span><br><span class="line">   AnnotationAttributes lazy = attributesFor(metadata, Lazy.class);</span><br><span class="line">   <span class="keyword">if</span> (lazy != <span class="keyword">null</span>) &#123;</span><br><span class="line">      abd.setLazyInit(lazy.getBoolean(<span class="string">&quot;value&quot;</span>));</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> <span class="keyword">if</span> (abd.getMetadata() != metadata) &#123;</span><br><span class="line">      lazy = attributesFor(abd.getMetadata(), Lazy.class);</span><br><span class="line">      <span class="keyword">if</span> (lazy != <span class="keyword">null</span>) &#123;</span><br><span class="line">         abd.setLazyInit(lazy.getBoolean(<span class="string">&quot;value&quot;</span>));</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (metadata.isAnnotated(Primary.class.getName())) &#123;</span><br><span class="line">      abd.setPrimary(<span class="keyword">true</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   AnnotationAttributes dependsOn = attributesFor(metadata, DependsOn.class);</span><br><span class="line">   <span class="keyword">if</span> (dependsOn != <span class="keyword">null</span>) &#123;</span><br><span class="line">      abd.setDependsOn(dependsOn.getStringArray(<span class="string">&quot;value&quot;</span>));</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   AnnotationAttributes role = attributesFor(metadata, Role.class);</span><br><span class="line">   <span class="keyword">if</span> (role != <span class="keyword">null</span>) &#123;</span><br><span class="line">      abd.setRole(role.getNumber(<span class="string">&quot;value&quot;</span>).intValue());</span><br><span class="line">   &#125;</span><br><span class="line">   AnnotationAttributes description = attributesFor(metadata, Description.class);</span><br><span class="line">   <span class="keyword">if</span> (description != <span class="keyword">null</span>) &#123;</span><br><span class="line">      abd.setDescription(description.getString(<span class="string">&quot;value&quot;</span>));</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>走完之后，注册中心肯定多了咱们的配置类</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211008213900796.png"/>



<ol>
<li>接下来就是想办法让主配置类里的配置生效</li>
<li>目前Spring就靠上面的4个后置处理器和一个主配置类白手起家了，开始我们后面最重要的refresh()容器刷新流程了</li>
</ol>
<h2 id="AbstractApplicationContext-refresh-开始容器刷新"><a href="#AbstractApplicationContext-refresh-开始容器刷新" class="headerlink" title="AbstractApplicationContext#refresh()开始容器刷新"></a>AbstractApplicationContext#refresh()开始容器刷新</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span>  <span class="comment">//容器刷新的十二大步。模板模式</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refresh</span><span class="params">()</span> <span class="keyword">throws</span> BeansException, IllegalStateException </span>&#123;</span><br><span class="line">   <span class="keyword">synchronized</span> (<span class="keyword">this</span>.startupShutdownMonitor) &#123;</span><br><span class="line">       <span class="comment">//容器启动过程状态的封装类</span></span><br><span class="line">      StartupStep contextRefresh = <span class="keyword">this</span>.applicationStartup.start(<span class="string">&quot;spring.context.refresh&quot;</span>);</span><br><span class="line"></span><br><span class="line">      <span class="comment">//准备上下文环境 Prepare this context for refreshing.</span></span><br><span class="line">      prepareRefresh();</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Tell the subclass to refresh the internal bean factory.</span></span><br><span class="line">      <span class="comment">// 工厂创建：BeanFactory第一次开始创建的时候,有xml解析逻辑。注解版这一步什么都没做，直接返回this()环节早就new好的工厂</span></span><br><span class="line">      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();</span><br><span class="line"></span><br><span class="line">      <span class="comment">//给容器中注册了环境信息作为单实例Bean方便后续自动装配；放了一些后置处理器处理（监听、xxAware功能） Prepare thebean factory for use in this context.</span></span><br><span class="line">      prepareBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         <span class="comment">//留给子类的模板方法，允许子类继续对工厂执行一些处理； Allows post-processing of the bean factory in context subclasses.</span></span><br><span class="line">         postProcessBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">         StartupStep beanPostProcess = <span class="keyword">this</span>.applicationStartup.start(<span class="string">&quot;spring.context.beans.post-process&quot;</span>);</span><br><span class="line">         <span class="comment">//【核心】工厂增强：执行所有的BeanFactory后置增强器；利用BeanFactory后置增强器对工厂进行修改或者增强,配置类会在这里进行解析。 Invoke factory processors registered as beans in the context.</span></span><br><span class="line">         invokeBeanFactoryPostProcessors(beanFactory);</span><br><span class="line"></span><br><span class="line">         <span class="comment">//【核心】注册所有的Bean的后置处理器 Register bean processors that intercept bean creation.</span></span><br><span class="line">         registerBeanPostProcessors(beanFactory);</span><br><span class="line">         beanPostProcess.end();</span><br><span class="line"></span><br><span class="line">         <span class="comment">//初始化国际化功能 Initialize message source for this context.</span></span><br><span class="line">         initMessageSource();</span><br><span class="line"></span><br><span class="line">         <span class="comment">//初始化事件多播功能（事件派发） Initialize event multicaster for this context.</span></span><br><span class="line">         initApplicationEventMulticaster();</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Initialize other special beans in specific context subclasses.</span></span><br><span class="line">         onRefresh();</span><br><span class="line"></span><br><span class="line">         <span class="comment">//注册监听器，从容器中获取所有的ApplicationListener； Check for listener beans and register them.</span></span><br><span class="line">         registerListeners();</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Instantiate all remaining (non-lazy-init) singletons.</span></span><br><span class="line">         <span class="comment">//【大核心】bean创建；完成 BeanFactory 初始化。（工厂里面所有的组件都好了）</span></span><br><span class="line">         finishBeanFactoryInitialization(beanFactory);</span><br><span class="line"></span><br><span class="line">         <span class="comment">//发布事件 Last step: publish corresponding event.</span></span><br><span class="line">         finishRefresh();</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">catch</span> (BeansException ex) &#123;</span><br><span class="line">         <span class="keyword">if</span> (logger.isWarnEnabled()) &#123;</span><br><span class="line">            logger.warn(<span class="string">&quot;Exception encountered during context initialization - &quot;</span> +</span><br><span class="line">                  <span class="string">&quot;cancelling refresh attempt: &quot;</span> + ex);</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Destroy already created singletons to avoid dangling resources.</span></span><br><span class="line">         destroyBeans();</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Reset &#x27;active&#x27; flag.</span></span><br><span class="line">         cancelRefresh(ex);</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Propagate exception to caller.</span></span><br><span class="line">         <span class="keyword">throw</span> ex;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">finally</span> &#123;</span><br><span class="line">         <span class="comment">// Reset common introspection caches in Spring&#x27;s core, since we</span></span><br><span class="line">         <span class="comment">// might not ever need metadata for singleton beans anymore...</span></span><br><span class="line">         resetCommonCaches();</span><br><span class="line">         contextRefresh.end();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="prepareRefresh-准备上下文环境"><a href="#prepareRefresh-准备上下文环境" class="headerlink" title="prepareRefresh()准备上下文环境"></a>prepareRefresh()准备上下文环境</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">prepareRefresh</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   <span class="comment">// Switch to active.</span></span><br><span class="line">   <span class="keyword">this</span>.startupDate = System.currentTimeMillis();</span><br><span class="line">   <span class="keyword">this</span>.closed.set(<span class="keyword">false</span>);</span><br><span class="line">   <span class="keyword">this</span>.active.set(<span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">      <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">         logger.trace(<span class="string">&quot;Refreshing &quot;</span> + <span class="keyword">this</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         logger.debug(<span class="string">&quot;Refreshing &quot;</span> + getDisplayName());</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//其他子容器自行实现（比如：WebApplicationContext） Initialize any placeholder property sources in the context environment.</span></span><br><span class="line">   initPropertySources();</span><br><span class="line"></span><br><span class="line">   <span class="comment">//准备环境变量信息 Validate that all properties marked as required are resolvable:</span></span><br><span class="line">   <span class="comment">// see ConfigurablePropertyResolver#setRequiredProperties</span></span><br><span class="line">   getEnvironment().validateRequiredProperties();</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 存储子容器早期运行的一些监听器； Store pre-refresh ApplicationListeners...</span></span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.earlyApplicationListeners == <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">this</span>.earlyApplicationListeners = <span class="keyword">new</span> LinkedHashSet&lt;&gt;(<span class="keyword">this</span>.applicationListeners);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// Reset local application listeners to pre-refresh state.</span></span><br><span class="line">      <span class="keyword">this</span>.applicationListeners.clear();</span><br><span class="line">      <span class="keyword">this</span>.applicationListeners.addAll(<span class="keyword">this</span>.earlyApplicationListeners);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//早期的一些事件存储到这里 Allow for the collection of early ApplicationEvents,</span></span><br><span class="line">   <span class="comment">// to be published once the multicaster is available...</span></span><br><span class="line">   <span class="keyword">this</span>.earlyApplicationEvents = <span class="keyword">new</span> LinkedHashSet&lt;&gt;();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="initPropertySources"><a href="#initPropertySources" class="headerlink" title="initPropertySources()"></a>initPropertySources()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initPropertySources</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   <span class="comment">// For subclasses: do nothing by default. 自行在此处加载一些自己感兴趣的信息。【WebApplicationContextUtils.initServletPropertySources】</span></span><br><span class="line">    <span class="comment">// web-ioc容器启动的时候一般在此加载当前应用的上下文信息（ApplicationContext）</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="prepareBeanFactory-给BeanFactory准备一些核心组件"><a href="#prepareBeanFactory-给BeanFactory准备一些核心组件" class="headerlink" title="prepareBeanFactory()给BeanFactory准备一些核心组件"></a>prepareBeanFactory()给BeanFactory准备一些核心组件</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">prepareBeanFactory</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">      <span class="comment">// Tell the internal bean factory to use the context&#x27;s class loader etc.</span></span><br><span class="line">      beanFactory.setBeanClassLoader(getClassLoader());</span><br><span class="line">      <span class="keyword">if</span> (!shouldIgnoreSpel) &#123; <span class="comment">//解释器模式  ，解析el表达式</span></span><br><span class="line">         beanFactory.setBeanExpressionResolver(<span class="keyword">new</span> StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));</span><br><span class="line">      &#125;</span><br><span class="line">      beanFactory.addPropertyEditorRegistrar(<span class="keyword">new</span> ResourceEditorRegistrar(<span class="keyword">this</span>, getEnvironment()));</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Configure the bean factory with context callbacks.</span></span><br><span class="line">      beanFactory.addBeanPostProcessor(<span class="keyword">new</span> ApplicationContextAwareProcessor(<span class="keyword">this</span>)); <span class="comment">//准备一个处理Aware接口功能的后置处理器</span></span><br><span class="line">      beanFactory.ignoreDependencyInterface(EnvironmentAware.class); <span class="comment">//告诉Spring先别管这些接口</span></span><br><span class="line">      beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);</span><br><span class="line">      beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);</span><br><span class="line">      beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);</span><br><span class="line">      beanFactory.ignoreDependencyInterface(MessageSourceAware.class);</span><br><span class="line">      beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);</span><br><span class="line">      beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);</span><br><span class="line"></span><br><span class="line">      <span class="comment">/*</span></span><br><span class="line"><span class="comment">      1.注册可以解析到的依赖，直接保存到容器的resolvableDependencies池里</span></span><br><span class="line"><span class="comment">      2.意思就是在我们自定义的类中，我们可以直接用@Autowired注解注入下面4个东西，并直接使用</span></span><br><span class="line"><span class="comment">      */</span></span><br><span class="line">      beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);</span><br><span class="line">      beanFactory.registerResolvableDependency(ResourceLoader.class, <span class="keyword">this</span>);</span><br><span class="line">      beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, <span class="keyword">this</span>);</span><br><span class="line">      beanFactory.registerResolvableDependency(ApplicationContext.class, <span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 注册应用监听器的探测器，用来探测应用中有哪些监听器。这也是一个后置处理器</span></span><br><span class="line">      beanFactory.addBeanPostProcessor(<span class="keyword">new</span> ApplicationListenerDetector(<span class="keyword">this</span>));</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Detect a LoadTimeWeaver and prepare for weaving, if found.</span></span><br><span class="line">      <span class="keyword">if</span> (!NativeDetector.inNativeImage() &amp;&amp; beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) &#123;</span><br><span class="line">         beanFactory.addBeanPostProcessor(<span class="keyword">new</span> LoadTimeWeaverAwareProcessor(beanFactory));</span><br><span class="line">         <span class="comment">// Set a temporary ClassLoader for type matching.</span></span><br><span class="line">         beanFactory.setTempClassLoader(<span class="keyword">new</span> ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">//注册默认组件： Register default environment beans.</span></span><br><span class="line">      <span class="keyword">if</span> (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) &#123;</span><br><span class="line">         beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) &#123;</span><br><span class="line">         beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) &#123;</span><br><span class="line">         beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) &#123;</span><br><span class="line">         beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">String ENVIRONMENT_BEAN_NAME = <span class="string">&quot;environment&quot;</span>;</span><br><span class="line"></span><br><span class="line">String SYSTEM_PROPERTIES_BEAN_NAME = <span class="string">&quot;systemProperties&quot;</span>;</span><br><span class="line"></span><br><span class="line">String SYSTEM_ENVIRONMENT_BEAN_NAME = <span class="string">&quot;systemEnvironment&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Name of the &#123;<span class="doctag">@link</span> ApplicationStartup&#125; bean in the factory.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 5.3</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">String APPLICATION_STARTUP_BEAN_NAME = <span class="string">&quot;applicationStartup&quot;</span>;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h3 id="postProcessBeanFactory-留给子类的模板方法"><a href="#postProcessBeanFactory-留给子类的模板方法" class="headerlink" title="postProcessBeanFactory()留给子类的模板方法"></a>postProcessBeanFactory()留给子类的模板方法</h3><p>这里是一个空方法，主要是留给子类实现，比如Web里的</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">postProcessBeanFactory</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009105903816.png"/>





<h3 id="invokeBeanFactoryPostProcessors-工厂增强【核心】"><a href="#invokeBeanFactoryPostProcessors-工厂增强【核心】" class="headerlink" title="invokeBeanFactoryPostProcessors()工厂增强【核心】"></a>invokeBeanFactoryPostProcessors()工厂增强【核心】</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">invokeBeanFactoryPostProcessors</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">   PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); <span class="comment">//执行所有的工厂增强器</span></span><br><span class="line">   <span class="comment">//上面的类叫：后置处理器的注册代理（门面模式-装饰模式）</span></span><br><span class="line">   <span class="comment">// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime</span></span><br><span class="line">   <span class="comment">// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)</span></span><br><span class="line">   <span class="keyword">if</span> (!NativeDetector.inNativeImage() &amp;&amp; beanFactory.getTempClassLoader() == <span class="keyword">null</span> &amp;&amp; beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) &#123;</span><br><span class="line">      beanFactory.addBeanPostProcessor(<span class="keyword">new</span> LoadTimeWeaverAwareProcessor(beanFactory));</span><br><span class="line">      beanFactory.setTempClassLoader(<span class="keyword">new</span> ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这一步有个很关键的后置处理器</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009113419863.png"/>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009114151034.png"/>



<h4 id="ConfigurationClassPostProcessor-postProcessBeanDefinitionRegistry-开始解析-Configuration标注的所有配置类相关信息，并生成Bean"><a href="#ConfigurationClassPostProcessor-postProcessBeanDefinitionRegistry-开始解析-Configuration标注的所有配置类相关信息，并生成Bean" class="headerlink" title="ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry()开始解析@Configuration标注的所有配置类相关信息，并生成Bean"></a>ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry()开始解析@Configuration标注的所有配置类相关信息，并生成Bean</h4><p><code>AnnotationConfigApplicationContext#register()</code>这里解析的是主配置类</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span> <span class="comment">//把配置类中所有bean的定义信息导入进来。</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessBeanDefinitionRegistry</span><span class="params">(BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">int</span> registryId = System.identityHashCode(registry);</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.registriesPostProcessed.contains(registryId)) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(</span><br><span class="line">               <span class="string">&quot;postProcessBeanDefinitionRegistry already called on this post-processor against &quot;</span> + registry);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.factoriesPostProcessed.contains(registryId)) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(</span><br><span class="line">               <span class="string">&quot;postProcessBeanFactory already called on this post-processor against &quot;</span> + registry);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">this</span>.registriesPostProcessed.add(registryId);</span><br><span class="line"></span><br><span class="line">      processConfigBeanDefinitions(registry); <span class="comment">//处理配置的BeanDefinition信息</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">processConfigBeanDefinitions</span><span class="params">(BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">	List&lt;BeanDefinitionHolder&gt; configCandidates = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">	String[] candidateNames = registry.getBeanDefinitionNames(); <span class="comment">//拿到工厂所有的bean定义信息</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span> (String beanName : candidateNames) &#123;</span><br><span class="line">		BeanDefinition beanDef = registry.getBeanDefinition(beanName);</span><br><span class="line">		<span class="keyword">if</span> (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">				logger.debug(<span class="string">&quot;Bean definition has already been processed as a configuration class: &quot;</span> + beanDef);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span> (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, <span class="keyword">this</span>.metadataReaderFactory)) &#123;</span><br><span class="line">			configCandidates.add(<span class="keyword">new</span> BeanDefinitionHolder(beanDef, beanName)); <span class="comment">//将配置类加到候选集合里面，等待处理</span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Return immediately if no @Configuration classes were found</span></span><br><span class="line">	<span class="keyword">if</span> (configCandidates.isEmpty()) &#123;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 对所有的配置类进行排序，Sort by previously determined @Order value, if applicable</span></span><br><span class="line">	configCandidates.sort((bd1, bd2) -&gt; &#123;</span><br><span class="line">		<span class="keyword">int</span> i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());</span><br><span class="line">		<span class="keyword">int</span> i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());</span><br><span class="line">		<span class="keyword">return</span> Integer.compare(i1, i2);</span><br><span class="line">	&#125;);</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Detect any custom bean name generation strategy supplied through the enclosing application context</span></span><br><span class="line">	SingletonBeanRegistry sbr = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">if</span> (registry <span class="keyword">instanceof</span> SingletonBeanRegistry) &#123;</span><br><span class="line">		sbr = (SingletonBeanRegistry) registry;</span><br><span class="line">		<span class="keyword">if</span> (!<span class="keyword">this</span>.localBeanNameGeneratorSet) &#123;</span><br><span class="line">			BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(</span><br><span class="line">					AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); <span class="comment">//getBean--getSingleton，获取创建一个internalConfigurationBeanNameGenerator来用来生成配置类的名字</span></span><br><span class="line">			<span class="keyword">if</span> (generator != <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">this</span>.componentScanBeanNameGenerator = generator;</span><br><span class="line">				<span class="keyword">this</span>.importBeanNameGenerator = generator;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.environment == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">this</span>.environment = <span class="keyword">new</span> StandardEnvironment();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//由ConfigurationClassParser解析每一个配置类 Parse each @Configuration class</span></span><br><span class="line">	ConfigurationClassParser parser = <span class="keyword">new</span> ConfigurationClassParser(</span><br><span class="line">			<span class="keyword">this</span>.metadataReaderFactory, <span class="keyword">this</span>.problemReporter, <span class="keyword">this</span>.environment,</span><br><span class="line">			<span class="keyword">this</span>.resourceLoader, <span class="keyword">this</span>.componentScanBeanNameGenerator, registry);</span><br><span class="line"></span><br><span class="line">	Set&lt;BeanDefinitionHolder&gt; candidates = <span class="keyword">new</span> LinkedHashSet&lt;&gt;(configCandidates);</span><br><span class="line">	Set&lt;ConfigurationClass&gt; alreadyParsed = <span class="keyword">new</span> HashSet&lt;&gt;(configCandidates.size());</span><br><span class="line">	<span class="keyword">do</span> &#123;</span><br><span class="line">		StartupStep processConfig = <span class="keyword">this</span>.applicationStartup.start(<span class="string">&quot;spring.context.config-classes.parse&quot;</span>);</span><br><span class="line">		parser.parse(candidates); <span class="comment">//解析配置类;所有需要扫描进来的组件的BeanDefinition信息都已经完成</span></span><br><span class="line">		parser.validate();</span><br><span class="line"></span><br><span class="line">		Set&lt;ConfigurationClass&gt; configClasses = <span class="keyword">new</span> LinkedHashSet&lt;&gt;(parser.getConfigurationClasses());</span><br><span class="line">		configClasses.removeAll(alreadyParsed);</span><br><span class="line">		<span class="comment">//每一个组件都可以当配置类，@Import之类的都能进行处理</span></span><br><span class="line">		<span class="comment">// Read the model and create bean definitions based on its content</span></span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">this</span>.reader == <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">this</span>.reader = <span class="keyword">new</span> ConfigurationClassBeanDefinitionReader(</span><br><span class="line">					registry, <span class="keyword">this</span>.sourceExtractor, <span class="keyword">this</span>.resourceLoader, <span class="keyword">this</span>.environment,</span><br><span class="line">					<span class="keyword">this</span>.importBeanNameGenerator, parser.getImportRegistry());</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">this</span>.reader.loadBeanDefinitions(configClasses);</span><br><span class="line">		alreadyParsed.addAll(configClasses);</span><br><span class="line">		processConfig.tag(<span class="string">&quot;classCount&quot;</span>, () -&gt; String.valueOf(configClasses.size())).end();</span><br><span class="line"></span><br><span class="line">		candidates.clear();</span><br><span class="line">		<span class="keyword">if</span> (registry.getBeanDefinitionCount() &gt; candidateNames.length) &#123;</span><br><span class="line">			String[] newCandidateNames = registry.getBeanDefinitionNames();</span><br><span class="line">			Set&lt;String&gt; oldCandidateNames = <span class="keyword">new</span> HashSet&lt;&gt;(Arrays.asList(candidateNames));</span><br><span class="line">			Set&lt;String&gt; alreadyParsedClasses = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line">			<span class="keyword">for</span> (ConfigurationClass configurationClass : alreadyParsed) &#123;</span><br><span class="line">				alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">for</span> (String candidateName : newCandidateNames) &#123;</span><br><span class="line">				<span class="keyword">if</span> (!oldCandidateNames.contains(candidateName)) &#123;</span><br><span class="line">					BeanDefinition bd = registry.getBeanDefinition(candidateName);</span><br><span class="line">					<span class="keyword">if</span> (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, <span class="keyword">this</span>.metadataReaderFactory) &amp;&amp;</span><br><span class="line">							!alreadyParsedClasses.contains(bd.getBeanClassName())) &#123;</span><br><span class="line">						candidates.add(<span class="keyword">new</span> BeanDefinitionHolder(bd, candidateName));</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			candidateNames = newCandidateNames;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">while</span> (!candidates.isEmpty());</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes</span></span><br><span class="line">	<span class="keyword">if</span> (sbr != <span class="keyword">null</span> &amp;&amp; !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) &#123;</span><br><span class="line">		sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.metadataReaderFactory <span class="keyword">instanceof</span> CachingMetadataReaderFactory) &#123;</span><br><span class="line">		<span class="comment">// Clear cache in externally provided MetadataReaderFactory; this is a no-op</span></span><br><span class="line">		<span class="comment">// for a shared cache since it&#x27;ll be cleared by the ApplicationContext.</span></span><br><span class="line">		((CachingMetadataReaderFactory) <span class="keyword">this</span>.metadataReaderFactory).clearCache();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009115044348.png"/>



<h4 id="ConfigurationClassParser-parse"><a href="#ConfigurationClassParser-parse" class="headerlink" title="ConfigurationClassParser#parse()"></a>ConfigurationClassParser#parse()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">parse</span><span class="params">(Set&lt;BeanDefinitionHolder&gt; configCandidates)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">for</span> (BeanDefinitionHolder holder : configCandidates) &#123;</span><br><span class="line">         BeanDefinition bd = holder.getBeanDefinition();</span><br><span class="line">         <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (bd <span class="keyword">instanceof</span> AnnotatedBeanDefinition) &#123;</span><br><span class="line">               parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (bd <span class="keyword">instanceof</span> AbstractBeanDefinition &amp;&amp; ((AbstractBeanDefinition) bd).hasBeanClass()) &#123;</span><br><span class="line">               parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">               parse(bd.getBeanClassName(), holder.getBeanName());</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">catch</span> (BeanDefinitionStoreException ex) &#123;</span><br><span class="line">            <span class="keyword">throw</span> ex;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(</span><br><span class="line">                  <span class="string">&quot;Failed to parse configuration class [&quot;</span> + bd.getBeanClassName() + <span class="string">&quot;]&quot;</span>, ex);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.deferredImportSelectorHandler.process();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//解析配置类</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">parse</span><span class="params">(AnnotationMetadata metadata, String beanName)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">	processConfigurationClass(<span class="keyword">new</span> ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">processConfigurationClass</span><span class="params">(ConfigurationClass configClass, Predicate&lt;String&gt; filter)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) &#123;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//Spring底层大量使用缓存来保证框架速度</span></span><br><span class="line">	ConfigurationClass existingClass = <span class="keyword">this</span>.configurationClasses.get(configClass);</span><br><span class="line">	<span class="keyword">if</span> (existingClass != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">if</span> (configClass.isImported()) &#123;</span><br><span class="line">			<span class="keyword">if</span> (existingClass.isImported()) &#123;</span><br><span class="line">				existingClass.mergeImportedBy(configClass);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="comment">// Otherwise ignore new imported config class; existing non-imported class overrides it.</span></span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="comment">// Explicit bean definition found, probably replacing an import.</span></span><br><span class="line">			<span class="comment">// Let&#x27;s remove the old one and go with the new one.</span></span><br><span class="line">			<span class="keyword">this</span>.configurationClasses.remove(configClass);</span><br><span class="line">			<span class="keyword">this</span>.knownSuperclasses.values().removeIf(configClass::equals);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Recursively process the configuration class and its superclass hierarchy.</span></span><br><span class="line">	SourceClass sourceClass = asSourceClass(configClass, filter);</span><br><span class="line">	<span class="keyword">do</span> &#123; <span class="comment">//解析配置类里面的所有注解，</span></span><br><span class="line">		sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">while</span> (sourceClass != <span class="keyword">null</span>);</span><br><span class="line">	<span class="comment">//只要这个配置类解析过，就放在已经解析好的集合中防止重复解析</span></span><br><span class="line">	<span class="keyword">this</span>.configurationClasses.put(configClass, configClass);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="ConfigurationClassParser-doProcessConfigurationClass-解析配置类中诸如-ComponentScan，-Import，-Bean等注解"><a href="#ConfigurationClassParser-doProcessConfigurationClass-解析配置类中诸如-ComponentScan，-Import，-Bean等注解" class="headerlink" title="ConfigurationClassParser#doProcessConfigurationClass()解析配置类中诸如@ComponentScan，@Import，@Bean等注解"></a>ConfigurationClassParser#doProcessConfigurationClass()解析配置类中诸如@ComponentScan，@Import，@Bean等注解</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Environment environment;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> BeanDefinitionRegistry registry;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> ComponentScanAnnotationParser componentScanParser;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;ConfigurationClass, ConfigurationClass&gt; configurationClasses = <span class="keyword">new</span> LinkedHashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, ConfigurationClass&gt; knownSuperclasses = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> SourceClass <span class="title">doProcessConfigurationClass</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">		ConfigurationClass configClass, SourceClass sourceClass, Predicate&lt;String&gt; filter)</span></span></span><br><span class="line"><span class="function">		<span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (configClass.getMetadata().isAnnotated(Component.class.getName())) &#123;</span><br><span class="line">		<span class="comment">// Recursively process any member (nested) classes first</span></span><br><span class="line">		processMemberClasses(configClass, sourceClass, filter);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Process any @PropertySource annotations</span></span><br><span class="line">	<span class="keyword">for</span> (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(</span><br><span class="line">			sourceClass.getMetadata(), PropertySources.class,</span><br><span class="line">			org.springframework.context.annotation.PropertySource.class)) &#123;</span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">this</span>.environment <span class="keyword">instanceof</span> ConfigurableEnvironment) &#123;</span><br><span class="line">			processPropertySource(propertySource);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			logger.info(<span class="string">&quot;Ignoring @PropertySource annotation on [&quot;</span> + sourceClass.getMetadata().getClassName() +</span><br><span class="line">					<span class="string">&quot;]. Reason: Environment must implement ConfigurableEnvironment&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Process any @ComponentScan annotations</span></span><br><span class="line">	Set&lt;AnnotationAttributes&gt; componentScans = AnnotationConfigUtils.attributesForRepeatable(</span><br><span class="line">			sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);</span><br><span class="line">	<span class="keyword">if</span> (!componentScans.isEmpty() &amp;&amp;</span><br><span class="line">			!<span class="keyword">this</span>.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) &#123;</span><br><span class="line">		<span class="keyword">for</span> (AnnotationAttributes componentScan : componentScans) &#123;</span><br><span class="line">			<span class="comment">//使用Scanner把ComponentScan指定的包下的所有组件都扫描进来 The config class is annotated with @ComponentScan -&gt; perform the scan immediately</span></span><br><span class="line">			Set&lt;BeanDefinitionHolder&gt; scannedBeanDefinitions =</span><br><span class="line">					<span class="keyword">this</span>.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());</span><br><span class="line">			<span class="comment">// Check the set of scanned definitions for any further config classes and parse recursively if needed</span></span><br><span class="line">			<span class="keyword">for</span> (BeanDefinitionHolder holder : scannedBeanDefinitions) &#123;</span><br><span class="line">				BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();</span><br><span class="line">				<span class="keyword">if</span> (bdCand == <span class="keyword">null</span>) &#123;</span><br><span class="line">					bdCand = holder.getBeanDefinition();</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">if</span> (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, <span class="keyword">this</span>.metadataReaderFactory)) &#123;</span><br><span class="line">					parse(bdCand.getBeanClassName(), holder.getBeanName());</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//处理@Import注解的地方【AOP就是利用这个地方导入一个后置处理器的】 Process any @Import annotations</span></span><br><span class="line">	processImports(configClass, sourceClass, getImports(sourceClass), filter, <span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//处理@ImportResource  Process any @ImportResource annotations</span></span><br><span class="line">	AnnotationAttributes importResource =</span><br><span class="line">			AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);</span><br><span class="line">	<span class="keyword">if</span> (importResource != <span class="keyword">null</span>) &#123;</span><br><span class="line">		String[] resources = importResource.getStringArray(<span class="string">&quot;locations&quot;</span>);</span><br><span class="line">		Class&lt;? extends BeanDefinitionReader&gt; readerClass = importResource.getClass(<span class="string">&quot;reader&quot;</span>);</span><br><span class="line">		<span class="keyword">for</span> (String resource : resources) &#123;</span><br><span class="line">			String resolvedResource = <span class="keyword">this</span>.environment.resolveRequiredPlaceholders(resource);</span><br><span class="line">			configClass.addImportedResource(resolvedResource, readerClass);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//处理@Bean Process individual @Bean methods</span></span><br><span class="line">	Set&lt;MethodMetadata&gt; beanMethods = retrieveBeanMethodMetadata(sourceClass);</span><br><span class="line">	<span class="keyword">for</span> (MethodMetadata methodMetadata : beanMethods) &#123;</span><br><span class="line">		configClass.addBeanMethod(<span class="keyword">new</span> BeanMethod(methodMetadata, configClass));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Process default methods on interfaces</span></span><br><span class="line">	processInterfaces(configClass, sourceClass);</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Process superclass, if any</span></span><br><span class="line">	<span class="keyword">if</span> (sourceClass.getMetadata().hasSuperClass()) &#123;</span><br><span class="line">		String superclass = sourceClass.getMetadata().getSuperClassName();</span><br><span class="line">		<span class="keyword">if</span> (superclass != <span class="keyword">null</span> &amp;&amp; !superclass.startsWith(<span class="string">&quot;java&quot;</span>) &amp;&amp;</span><br><span class="line">				!<span class="keyword">this</span>.knownSuperclasses.containsKey(superclass)) &#123;</span><br><span class="line">			<span class="keyword">this</span>.knownSuperclasses.put(superclass, configClass);</span><br><span class="line">			<span class="comment">// Superclass found, return its annotation metadata and recurse</span></span><br><span class="line">			<span class="keyword">return</span> sourceClass.getSuperClass();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// No superclass -&gt; processing is complete</span></span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h4 id="ComponentScanAnnotationParser-parse-具体如何解析-ComponentScan注解。这里也是-Component注解生效的地方"><a href="#ComponentScanAnnotationParser-parse-具体如何解析-ComponentScan注解。这里也是-Component注解生效的地方" class="headerlink" title="ComponentScanAnnotationParser#parse()具体如何解析@ComponentScan注解。这里也是@Component注解生效的地方"></a>ComponentScanAnnotationParser#parse()具体如何解析@ComponentScan注解。这里也是@Component注解生效的地方</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Set&lt;BeanDefinitionHolder&gt; <span class="title">parse</span><span class="params">(AnnotationAttributes componentScan, <span class="keyword">final</span> String declaringClass)</span> </span>&#123;</span><br><span class="line">   ClassPathBeanDefinitionScanner scanner = <span class="keyword">new</span> ClassPathBeanDefinitionScanner(<span class="keyword">this</span>.registry,</span><br><span class="line">componentScan.getBoolean(<span class="string">&quot;useDefaultFilters&quot;</span>), <span class="keyword">this</span>.environment, <span class="keyword">this</span>.resourceLoader);</span><br><span class="line">   <span class="comment">// ...省略不重要</span></span><br><span class="line">   <span class="keyword">return</span> scanner.doScan(StringUtils.toStringArray(basePackages)); <span class="comment">//扫描器进行扫描</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="ClassPathBeanDefinitionScanner-doScan"><a href="#ClassPathBeanDefinitionScanner-doScan" class="headerlink" title="ClassPathBeanDefinitionScanner#doScan()"></a>ClassPathBeanDefinitionScanner#doScan()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassPathBeanDefinitionScanner</span> <span class="keyword">extends</span> <span class="title">ClassPathScanningCandidateComponentProvider</span></span>&#123;  </span><br><span class="line">    </span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    </span><br><span class="line">	<span class="function"><span class="keyword">protected</span> Set&lt;BeanDefinitionHolder&gt; <span class="title">doScan</span><span class="params">(String... basePackages)</span> </span>&#123;</span><br><span class="line">       Assert.notEmpty(basePackages, <span class="string">&quot;At least one base package must be specified&quot;</span>);</span><br><span class="line">       Set&lt;BeanDefinitionHolder&gt; beanDefinitions = <span class="keyword">new</span> LinkedHashSet&lt;&gt;();</span><br><span class="line">       <span class="keyword">for</span> (String basePackage : basePackages) &#123;</span><br><span class="line">          Set&lt;BeanDefinition&gt; candidates = findCandidateComponents(basePackage); <span class="comment">//找到候选组件（我们需要扫描进来的组件），这里是调用父类的方法</span></span><br><span class="line">          <span class="keyword">for</span> (BeanDefinition candidate : candidates) &#123;</span><br><span class="line">             ScopeMetadata scopeMetadata = <span class="keyword">this</span>.scopeMetadataResolver.resolveScopeMetadata(candidate);</span><br><span class="line">             candidate.setScope(scopeMetadata.getScopeName());</span><br><span class="line">             String beanName = <span class="keyword">this</span>.beanNameGenerator.generateBeanName(candidate, <span class="keyword">this</span>.registry);</span><br><span class="line">             <span class="keyword">if</span> (candidate <span class="keyword">instanceof</span> AbstractBeanDefinition) &#123;</span><br><span class="line">                postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);</span><br><span class="line">             &#125;</span><br><span class="line">             <span class="keyword">if</span> (candidate <span class="keyword">instanceof</span> AnnotatedBeanDefinition) &#123;</span><br><span class="line">                AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);</span><br><span class="line">             &#125;</span><br><span class="line">             <span class="keyword">if</span> (checkCandidate(beanName, candidate)) &#123;</span><br><span class="line">                BeanDefinitionHolder definitionHolder = <span class="keyword">new</span> BeanDefinitionHolder(candidate, beanName);</span><br><span class="line">                definitionHolder =</span><br><span class="line">                      AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, <span class="keyword">this</span>.registry);</span><br><span class="line">                beanDefinitions.add(definitionHolder);</span><br><span class="line">                registerBeanDefinition(definitionHolder, <span class="keyword">this</span>.registry);</span><br><span class="line">             &#125;</span><br><span class="line">          &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> beanDefinitions;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="ClassPathScanningCandidateComponentProvider-findCandidateComponents"><a href="#ClassPathScanningCandidateComponentProvider-findCandidateComponents" class="headerlink" title="ClassPathScanningCandidateComponentProvider#findCandidateComponents()"></a>ClassPathScanningCandidateComponentProvider#findCandidateComponents()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> Set&lt;BeanDefinition&gt; <span class="title">findCandidateComponents</span><span class="params">(String basePackage)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.componentsIndex != <span class="keyword">null</span> &amp;&amp; indexSupportsIncludeFilters()) &#123;</span><br><span class="line">         <span class="keyword">return</span> addCandidateComponentsFromIndex(<span class="keyword">this</span>.componentsIndex, basePackage);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="keyword">return</span> scanCandidateComponents(basePackage); <span class="comment">//扫描所有组件</span></span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> Set&lt;BeanDefinition&gt; <span class="title">scanCandidateComponents</span><span class="params">(String basePackage)</span> </span>&#123;</span><br><span class="line">	Set&lt;BeanDefinition&gt; candidates = <span class="keyword">new</span> LinkedHashSet&lt;&gt;();</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +</span><br><span class="line">				resolveBasePackage(basePackage) + <span class="string">&#x27;/&#x27;</span> + <span class="keyword">this</span>.resourcePattern;</span><br><span class="line">		Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);</span><br><span class="line">		<span class="keyword">boolean</span> traceEnabled = logger.isTraceEnabled();</span><br><span class="line">		<span class="keyword">boolean</span> debugEnabled = logger.isDebugEnabled();</span><br><span class="line">		<span class="keyword">for</span> (Resource resource : resources) &#123;</span><br><span class="line">			<span class="keyword">if</span> (traceEnabled) &#123;</span><br><span class="line">				logger.trace(<span class="string">&quot;Scanning &quot;</span> + resource);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">if</span> (resource.isReadable()) &#123;</span><br><span class="line">				<span class="keyword">try</span> &#123; <span class="comment">//生成每一个资源的元数据信息</span></span><br><span class="line">					MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);</span><br><span class="line">					<span class="keyword">if</span> (isCandidateComponent(metadataReader)) &#123; <span class="comment">//如果当前类在扫描范围</span></span><br><span class="line">						ScannedGenericBeanDefinition sbd = <span class="keyword">new</span> ScannedGenericBeanDefinition(metadataReader);</span><br><span class="line">						sbd.setSource(resource);</span><br><span class="line">						<span class="keyword">if</span> (isCandidateComponent(sbd)) &#123;</span><br><span class="line">							<span class="keyword">if</span> (debugEnabled) &#123;</span><br><span class="line">								logger.debug(<span class="string">&quot;Identified candidate component class: &quot;</span> + resource);</span><br><span class="line">							&#125;</span><br><span class="line">							candidates.add(sbd);</span><br><span class="line">						&#125;</span><br><span class="line">						<span class="keyword">else</span> &#123;</span><br><span class="line">							<span class="keyword">if</span> (debugEnabled) &#123;</span><br><span class="line">								logger.debug(<span class="string">&quot;Ignored because not a concrete top-level class: &quot;</span> + resource);</span><br><span class="line">							&#125;</span><br><span class="line">						&#125;</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="keyword">else</span> &#123;</span><br><span class="line">						<span class="keyword">if</span> (traceEnabled) &#123;</span><br><span class="line">							logger.trace(<span class="string">&quot;Ignored because not matching any filter: &quot;</span> + resource);</span><br><span class="line">						&#125;</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">					<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(</span><br><span class="line">							<span class="string">&quot;Failed to read candidate component class: &quot;</span> + resource, ex);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> &#123;</span><br><span class="line">				<span class="keyword">if</span> (traceEnabled) &#123;</span><br><span class="line">					logger.trace(<span class="string">&quot;Ignored because not readable: &quot;</span> + resource);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (IOException ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(<span class="string">&quot;I/O failure during classpath scanning&quot;</span>, ex);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> candidates;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>拿到所有类(资源),不管你有没有标@Component注解。然后挨个遍历每一个资源是不是候选的组件(根据前面准备的一些条件，在这里进行判断)</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009145119146.png"/>





<p>最后我们看一下执行完之后的BeanDefinition信息</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009150338205.png"/>



<h3 id="registerBeanPostProcessors-注册所有的Bean后置处理器"><a href="#registerBeanPostProcessors-注册所有的Bean后置处理器" class="headerlink" title="registerBeanPostProcessors()注册所有的Bean后置处理器"></a>registerBeanPostProcessors()注册所有的Bean后置处理器</h3><p>前面讲过</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">registerBeanPostProcessors</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">   PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, <span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="PostProcessorRegistrationDelegate-registerBeanPostProcessors"><a href="#PostProcessorRegistrationDelegate-registerBeanPostProcessors" class="headerlink" title="PostProcessorRegistrationDelegate#registerBeanPostProcessors()"></a>PostProcessorRegistrationDelegate#registerBeanPostProcessors()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">registerBeanPostProcessors</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">      ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// WARNING: Although it may appear that the body of this method can be easily</span></span><br><span class="line">   <span class="comment">// refactored to avoid the use of multiple loops and multiple lists, the use</span></span><br><span class="line">   <span class="comment">// of multiple lists and multiple passes over the names of processors is</span></span><br><span class="line">   <span class="comment">// intentional. We must ensure that we honor the contracts for PriorityOrdered</span></span><br><span class="line">   <span class="comment">// and Ordered processors. Specifically, we must NOT cause processors to be</span></span><br><span class="line">   <span class="comment">// instantiated (via getBean() invocations) or registered in the ApplicationContext</span></span><br><span class="line">   <span class="comment">// in the wrong order.</span></span><br><span class="line">   <span class="comment">//</span></span><br><span class="line">   <span class="comment">// Before submitting a pull request (PR) to change this method, please review the</span></span><br><span class="line">   <span class="comment">// list of all declined PRs involving changes to PostProcessorRegistrationDelegate</span></span><br><span class="line">   <span class="comment">// to ensure that your proposal does not result in a breaking change:</span></span><br><span class="line">   <span class="comment">// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22</span></span><br><span class="line">   <span class="comment">//获取到容器中所有的 BeanPostProcessor； Bean的后置处理器</span></span><br><span class="line">   String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Register BeanPostProcessorChecker that logs an info message when</span></span><br><span class="line">   <span class="comment">// a bean is created during BeanPostProcessor instantiation, i.e. when</span></span><br><span class="line">   <span class="comment">// a bean is not eligible for getting processed by all BeanPostProcessors.</span></span><br><span class="line">   <span class="keyword">int</span> beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + <span class="number">1</span> + postProcessorNames.length;</span><br><span class="line">   beanFactory.addBeanPostProcessor(<span class="keyword">new</span> BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Separate between BeanPostProcessors that implement PriorityOrdered,</span></span><br><span class="line">   <span class="comment">// Ordered, and the rest.</span></span><br><span class="line">   List&lt;BeanPostProcessor&gt; priorityOrderedPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   List&lt;BeanPostProcessor&gt; internalPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   List&lt;String&gt; orderedPostProcessorNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   List&lt;String&gt; nonOrderedPostProcessorNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   <span class="keyword">for</span> (String ppName : postProcessorNames) &#123;</span><br><span class="line">      <span class="keyword">if</span> (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) &#123;  <span class="comment">//获取所有实现了 PriorityOrdered 的 BeanPostProcessor</span></span><br><span class="line">         BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);</span><br><span class="line">         priorityOrderedPostProcessors.add(pp);</span><br><span class="line">         <span class="keyword">if</span> (pp <span class="keyword">instanceof</span> MergedBeanDefinitionPostProcessor) &#123;</span><br><span class="line">            internalPostProcessors.add(pp);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (beanFactory.isTypeMatch(ppName, Ordered.class)) &#123;</span><br><span class="line">         orderedPostProcessorNames.add(ppName);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         nonOrderedPostProcessorNames.add(ppName);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//首先，注册所有的实现了 PriorityOrdered 的 BeanPostProcessor ；  First, register the BeanPostProcessors that implement PriorityOrdered.</span></span><br><span class="line">   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);</span><br><span class="line">   registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);</span><br><span class="line"></span><br><span class="line">   <span class="comment">//接下来，注册所有的实现了 Ordered 的 BeanPostProcessor  Next, register the BeanPostProcessors that implement Ordered.</span></span><br><span class="line">   List&lt;BeanPostProcessor&gt; orderedPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;(orderedPostProcessorNames.size());</span><br><span class="line">   <span class="keyword">for</span> (String ppName : orderedPostProcessorNames) &#123;</span><br><span class="line">      BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);</span><br><span class="line">      orderedPostProcessors.add(pp);</span><br><span class="line">      <span class="keyword">if</span> (pp <span class="keyword">instanceof</span> MergedBeanDefinitionPostProcessor) &#123;</span><br><span class="line">         internalPostProcessors.add(pp);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   sortPostProcessors(orderedPostProcessors, beanFactory);</span><br><span class="line">   registerBeanPostProcessors(beanFactory, orderedPostProcessors);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 最后，注册所有普通的 BeanPostProcessor ；Now, register all regular BeanPostProcessors.</span></span><br><span class="line">   List&lt;BeanPostProcessor&gt; nonOrderedPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;(nonOrderedPostProcessorNames.size());</span><br><span class="line">   <span class="keyword">for</span> (String ppName : nonOrderedPostProcessorNames) &#123;</span><br><span class="line">      BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); <span class="comment">//从容器中获取这个组件</span></span><br><span class="line">      nonOrderedPostProcessors.add(pp);</span><br><span class="line">      <span class="keyword">if</span> (pp <span class="keyword">instanceof</span> MergedBeanDefinitionPostProcessor) &#123;</span><br><span class="line">         internalPostProcessors.add(pp);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);</span><br><span class="line"></span><br><span class="line">   <span class="comment">//最后，重新注册所有internal的BeanPostProcessors  Finally, re-register all internal BeanPostProcessors.</span></span><br><span class="line">   sortPostProcessors(internalPostProcessors, beanFactory);</span><br><span class="line">   registerBeanPostProcessors(beanFactory, internalPostProcessors);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 重新注册一下这个后置处理器 Re-register post-processor for detecting inner beans as ApplicationListeners,</span></span><br><span class="line">   <span class="comment">// 把他放到后置处理器的最后一位； moving it to the end of the processor chain (for picking up proxies etc).</span></span><br><span class="line">   beanFactory.addBeanPostProcessor(<span class="keyword">new</span> ApplicationListenerDetector(applicationContext));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="initMessageSource"><a href="#initMessageSource" class="headerlink" title="initMessageSource()"></a>initMessageSource()</h3><p>初始化国际化功能</p>
<ol>
<li>看容器中是否有MessageSource的定义信息</li>
<li>如果没有就注册一个默认的</li>
<li>把国际化组件(MessageSource) 放到单例池中</li>
</ol>
<h3 id="initApplicationEventMulticaster"><a href="#initApplicationEventMulticaster" class="headerlink" title="initApplicationEventMulticaster()"></a>initApplicationEventMulticaster()</h3><p>初始化事件多播功能（事件派发）</p>
<ol>
<li>看容器中是否有applicationEventMulticaster的定义信息，按照id找</li>
<li>如果没有就注册一个默认的</li>
<li>把事件多播器组件(ApplicationEventMulticaster) 放到单例池中</li>
</ol>
<h3 id="onRefresh-模板方法留给子类继续增强处理"><a href="#onRefresh-模板方法留给子类继续增强处理" class="headerlink" title="onRefresh()模板方法留给子类继续增强处理"></a>onRefresh()模板方法留给子类继续增强处理</h3><p>留给子类继续增强处理，模板模式。</p>
<h3 id="registerListeners"><a href="#registerListeners" class="headerlink" title="registerListeners()"></a>registerListeners()</h3><p>注册监听器，从容器中获取所有的ApplicationListener</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/** 多播器和监听器是观察者模式（里面包含了所有的监听器）</span></span><br><span class="line"><span class="comment"> * Add beans that implement ApplicationListener as listeners.</span></span><br><span class="line"><span class="comment"> * Doesn&#x27;t affect other listeners, which can be added without being beans.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">registerListeners</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   <span class="comment">//把所有监听器保存到多播器的集合中 Register statically specified listeners first.</span></span><br><span class="line">   <span class="keyword">for</span> (ApplicationListener&lt;?&gt; listener : getApplicationListeners()) &#123;</span><br><span class="line">      getApplicationEventMulticaster().addApplicationListener(listener);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Do not initialize FactoryBeans here: We need to leave all regular beans</span></span><br><span class="line">   <span class="comment">// uninitialized to let post-processors apply to them! 获取ApplicationListener在ioc容器中注册的bean的名字</span></span><br><span class="line">   String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line">   <span class="keyword">for</span> (String listenerBeanName : listenerBeanNames) &#123;</span><br><span class="line">      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); <span class="comment">//获取所有的容器中的监听器，并保存他们的名字</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//派发之前攒的一些早期事件 Publish early application events now that we finally have a multicaster...</span></span><br><span class="line">   Set&lt;ApplicationEvent&gt; earlyEventsToProcess = <span class="keyword">this</span>.earlyApplicationEvents;</span><br><span class="line">   <span class="keyword">this</span>.earlyApplicationEvents = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">if</span> (!CollectionUtils.isEmpty(earlyEventsToProcess)) &#123;</span><br><span class="line">      <span class="keyword">for</span> (ApplicationEvent earlyEvent : earlyEventsToProcess) &#123;</span><br><span class="line">         getApplicationEventMulticaster().multicastEvent(earlyEvent);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>监听器也是一个重点，后面细讲</p>
<h3 id="finishBeanFactoryInitialization-正式创建所有普通Bean"><a href="#finishBeanFactoryInitialization-正式创建所有普通Bean" class="headerlink" title="finishBeanFactoryInitialization()正式创建所有普通Bean"></a>finishBeanFactoryInitialization()正式创建所有普通Bean</h3><p>前面Bean的初始化流程讲的很仔细了</p>
<ol>
<li>主要就是遍历循环所有BeanDefinition里的BeanName，挨个创建Bean对象。注意BeanPostProcessor这些不算普通Bean，在registerBeanPostProcessors()，invokeBeanFactoryPostProcessors()已经创建完了，因为在普通Bean创建的过程中，后置处理器可能需要参与进来，所以需要比普通Bean提前创建好</li>
<li>最后执行SmartInitializingSingleton.afterSingletonsInstantiated后初始化</li>
</ol>
<h3 id="finishRefresh-主要是发送容器刷新完成的事件"><a href="#finishRefresh-主要是发送容器刷新完成的事件" class="headerlink" title="finishRefresh()主要是发送容器刷新完成的事件"></a>finishRefresh()主要是发送容器刷新完成的事件</h3><p>最后进行一些清理和事件发送等</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">finishRefresh</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   <span class="comment">// Clear context-level resource caches (such as ASM metadata from scanning).</span></span><br><span class="line">   clearResourceCaches();</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Initialize lifecycle processor for this context.</span></span><br><span class="line">   initLifecycleProcessor();</span><br><span class="line"></span><br><span class="line">   <span class="comment">//告诉LifecycleProcessor容器onRefresh Propagate refresh to lifecycle processor first.</span></span><br><span class="line">   getLifecycleProcessor().onRefresh();</span><br><span class="line"></span><br><span class="line">   <span class="comment">//发布事件 Publish the final event.</span></span><br><span class="line">   publishEvent(<span class="keyword">new</span> ContextRefreshedEvent(<span class="keyword">this</span>));</span><br><span class="line"></span><br><span class="line">   <span class="comment">//jconsole（暴露MBean端点信息） Participate in LiveBeansView MBean, if active.</span></span><br><span class="line">   <span class="keyword">if</span> (!NativeDetector.inNativeImage()) &#123;</span><br><span class="line">      LiveBeansView.registerApplicationContext(<span class="keyword">this</span>);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>自此over</p>
<h1 id="补充：循环引用解决方案"><a href="#补充：循环引用解决方案" class="headerlink" title="补充：循环引用解决方案"></a>补充：循环引用解决方案</h1><blockquote>
<p>单开一节，讲一下之前一直忽略的这个。其实很简单的一个东西，被网上搞的很难一样。</p>
</blockquote>
<h2 id="测试类"><a href="#测试类" class="headerlink" title="测试类"></a>测试类</h2><h3 id="A"><a href="#A" class="headerlink" title="A"></a>A</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> B b;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">A</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;A...构造....&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setB</span><span class="params">(B b)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.b = b;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="B"><a href="#B" class="headerlink" title="B"></a>B</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">B</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> A a;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">B</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;B...构造....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Autowired</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setA</span><span class="params">(A a)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.a = a;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这就是循环引用的场景，这种写法由于Spring内部获取Bean都是通过getBean方法来获取，就造成了下面的死循环。我们来看看Spring是怎么解决的。</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20210928203211130.png">



<h2 id="核心代码"><a href="#核心代码" class="headerlink" title="核心代码"></a>核心代码</h2><h3 id="AbstractBeanFactory"><a href="#AbstractBeanFactory" class="headerlink" title="AbstractBeanFactory"></a>AbstractBeanFactory</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"> <span class="keyword">protected</span> &lt;T&gt; <span class="function">T <span class="title">doGetBean</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">       String name, <span class="meta">@Nullable</span> Class&lt;T&gt; requiredType, <span class="meta">@Nullable</span> Object[] args, <span class="keyword">boolean</span> typeCheckOnly)</span></span></span><br><span class="line"><span class="function">       <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line"></span><br><span class="line">    String beanName = transformedBeanName(name); <span class="comment">//转换Bean名字</span></span><br><span class="line">    Object beanInstance;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 先检查单实例bean的缓存 Eagerly check singleton cache for manually registered singletons.</span></span><br><span class="line">    <span class="comment">// ☆☆☆ pos_1</span></span><br><span class="line">    Object sharedInstance = getSingleton(beanName); <span class="comment">//检查缓存中有没有，如果是第一次获取肯定是没有的     </span></span><br><span class="line">    <span class="keyword">if</span> (sharedInstance != <span class="keyword">null</span> &amp;&amp; args == <span class="keyword">null</span>) &#123;</span><br><span class="line">       <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">          <span class="keyword">if</span> (isSingletonCurrentlyInCreation(beanName)) &#123;</span><br><span class="line">	<span class="comment">// ...</span></span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">else</span> &#123;</span><br><span class="line">             <span class="comment">// ..</span></span><br><span class="line">          &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">else</span> &#123; <span class="comment">//默认第一次获取组件都会进入else环节</span></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line">          <span class="comment">// 创建bean的实例；Create bean instance.</span></span><br><span class="line">          <span class="keyword">if</span> (mbd.isSingleton()) &#123;</span><br><span class="line">             <span class="comment">// ☆☆☆ pos_2</span></span><br><span class="line">             sharedInstance = getSingleton(beanName, () -&gt; &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                   <span class="keyword">return</span> createBean(beanName, mbd, args);  <span class="comment">//创建bean对象的实例</span></span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">catch</span> (BeansException ex) &#123;</span><br><span class="line">                   destroySingleton(beanName);</span><br><span class="line">                   <span class="keyword">throw</span> ex;</span><br><span class="line">                &#125;</span><br><span class="line">             &#125;); <span class="comment">//看当前bean是否是FactoryBean</span></span><br><span class="line">             beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);</span><br><span class="line">          &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>



<h3 id="DefaultSingletonBeanRegistry"><a href="#DefaultSingletonBeanRegistry" class="headerlink" title="DefaultSingletonBeanRegistry"></a>DefaultSingletonBeanRegistry</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">getSingleton</span><span class="params">(String beanName)</span> </span>&#123;</span><br><span class="line">      <span class="comment">// ☆☆☆ pos_3</span></span><br><span class="line">      <span class="keyword">return</span> getSingleton(beanName, <span class="keyword">true</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Return the (raw) singleton object registered under the given name.</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;Checks already instantiated singletons and also allows for an early</span></span><br><span class="line"><span class="comment">    * reference to a currently created singleton (resolving a circular reference).</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> beanName the name of the bean to look for</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> allowEarlyReference whether early references should be created or not</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span> the registered singleton object, or &#123;<span class="doctag">@code</span> null&#125; if none found</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">  <span class="comment">//☆☆☆ pos_4</span></span><br><span class="line">   <span class="meta">@Nullable</span>  <span class="comment">//双检查锁</span></span><br><span class="line">   <span class="function"><span class="keyword">protected</span> Object <span class="title">getSingleton</span><span class="params">(String beanName, <span class="keyword">boolean</span> allowEarlyReference)</span> </span>&#123;</span><br><span class="line">      <span class="comment">//先检查单例缓存池，获取当前对象  Quick check for existing instance without full singleton lock</span></span><br><span class="line">      Object singletonObject = <span class="keyword">this</span>.singletonObjects.get(beanName); <span class="comment">//一级缓存</span></span><br><span class="line">      <span class="keyword">if</span> (singletonObject == <span class="keyword">null</span> &amp;&amp; isSingletonCurrentlyInCreation(beanName)) &#123; <span class="comment">//如果当前bean正在创建过程中，而且缓存中没有则继续</span></span><br><span class="line">         singletonObject = <span class="keyword">this</span>.earlySingletonObjects.get(beanName); <span class="comment">//二级</span></span><br><span class="line">         <span class="keyword">if</span> (singletonObject == <span class="keyword">null</span> &amp;&amp; allowEarlyReference) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (<span class="keyword">this</span>.singletonObjects) &#123;</span><br><span class="line">               <span class="comment">// Consistent creation of early reference within full singleton lock</span></span><br><span class="line">               singletonObject = <span class="keyword">this</span>.singletonObjects.get(beanName);</span><br><span class="line">               <span class="keyword">if</span> (singletonObject == <span class="keyword">null</span>) &#123;</span><br><span class="line">                  singletonObject = <span class="keyword">this</span>.earlySingletonObjects.get(beanName);</span><br><span class="line">                  <span class="keyword">if</span> (singletonObject == <span class="keyword">null</span>) &#123;</span><br><span class="line">                     ObjectFactory&lt;?&gt; singletonFactory = <span class="keyword">this</span>.singletonFactories.get(beanName); <span class="comment">//三级</span></span><br><span class="line">                     <span class="keyword">if</span> (singletonFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        singletonObject = singletonFactory.getObject();</span><br><span class="line">                        <span class="keyword">this</span>.earlySingletonObjects.put(beanName, singletonObject);</span><br><span class="line">                        <span class="keyword">this</span>.singletonFactories.remove(beanName);</span><br><span class="line">                     &#125;</span><br><span class="line">                  &#125;</span><br><span class="line">               &#125;</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> singletonObject;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// ☆☆☆ pos_5</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getSingleton</span><span class="params">(String beanName, ObjectFactory&lt;?&gt; singletonFactory)</span> </span>&#123;</span><br><span class="line">	Assert.notNull(beanName, <span class="string">&quot;Bean name must not be null&quot;</span>);</span><br><span class="line">	<span class="keyword">synchronized</span> (<span class="keyword">this</span>.singletonObjects) &#123;</span><br><span class="line">		Object singletonObject = <span class="keyword">this</span>.singletonObjects.get(beanName);<span class="comment">//再检查一次单例池</span></span><br><span class="line">		<span class="keyword">if</span> (singletonObject == <span class="keyword">null</span>) &#123; <span class="comment">//单实例池子里面没有当前对象（说明没有创建完成）</span></span><br><span class="line">			<span class="keyword">if</span> (<span class="keyword">this</span>.singletonsCurrentlyInDestruction) &#123;</span><br><span class="line">				<span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationNotAllowedException(beanName,</span><br><span class="line">						<span class="string">&quot;Singleton bean creation not allowed while singletons of this factory are in destruction &quot;</span> +</span><br><span class="line">						<span class="string">&quot;(Do not request a bean from a BeanFactory in a destroy method implementation!)&quot;</span>);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">				logger.debug(<span class="string">&quot;Creating shared instance of singleton bean &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">			&#125;</span><br><span class="line">                <span class="comment">// ☆☆☆ pos_6</span></span><br><span class="line">			beforeSingletonCreation(beanName); <span class="comment">//单实例创建之前，这个就是加到</span></span><br><span class="line">			<span class="keyword">boolean</span> newSingleton = <span class="keyword">false</span>;</span><br><span class="line">			<span class="keyword">boolean</span> recordSuppressedExceptions = (<span class="keyword">this</span>.suppressedExceptions == <span class="keyword">null</span>);</span><br><span class="line">			<span class="keyword">if</span> (recordSuppressedExceptions) &#123;</span><br><span class="line">				<span class="keyword">this</span>.suppressedExceptions = <span class="keyword">new</span> LinkedHashSet&lt;&gt;();</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				singletonObject = singletonFactory.getObject();<span class="comment">//会调用lamda表达式的内容，真正创建对象</span></span><br><span class="line">				newSingleton = <span class="keyword">true</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">catch</span> (IllegalStateException ex) &#123;</span><br><span class="line">				<span class="comment">// Has the singleton object implicitly appeared in the meantime -&gt;</span></span><br><span class="line">				<span class="comment">// if yes, proceed with it since the exception indicates that state.</span></span><br><span class="line">                   <span class="comment">// ☆☆☆ pos_7</span></span><br><span class="line">				singletonObject = <span class="keyword">this</span>.singletonObjects.get(beanName);</span><br><span class="line">				<span class="keyword">if</span> (singletonObject == <span class="keyword">null</span>) &#123;</span><br><span class="line">					<span class="keyword">throw</span> ex;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">catch</span> (BeanCreationException ex) &#123;</span><br><span class="line">				<span class="comment">// ...</span></span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">finally</span> &#123;</span><br><span class="line">				<span class="keyword">if</span> (recordSuppressedExceptions) &#123;</span><br><span class="line">					<span class="keyword">this</span>.suppressedExceptions = <span class="keyword">null</span>;</span><br><span class="line">				&#125;</span><br><span class="line">				afterSingletonCreation(beanName);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">if</span> (newSingleton) &#123;</span><br><span class="line">				addSingleton(beanName, singletonObject);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> singletonObject;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 加到singletonsCurrentlyInCreation</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">beforeSingletonCreation</span><span class="params">(String beanName)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (!<span class="keyword">this</span>.inCreationCheckExclusions.contains(beanName) &amp;&amp; !<span class="keyword">this</span>.singletonsCurrentlyInCreation.add(beanName)) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> BeanCurrentlyInCreationException(beanName);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="AbstractAutowireCapableBeanFactory"><a href="#AbstractAutowireCapableBeanFactory" class="headerlink" title="AbstractAutowireCapableBeanFactory"></a>AbstractAutowireCapableBeanFactory</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">protected</span> Object <span class="title">doCreateBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">       <span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Instantiate the bean.</span></span><br><span class="line">    BeanWrapper instanceWrapper = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">if</span> (mbd.isSingleton()) &#123; <span class="comment">//是否单例的</span></span><br><span class="line">       instanceWrapper = <span class="keyword">this</span>.factoryBeanInstanceCache.remove(beanName);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (instanceWrapper == <span class="keyword">null</span>) &#123;</span><br><span class="line">       <span class="comment">//创建Bean的实例,默认使用无参构造器创建的对象，组件的原始对象就创建了 ☆☆☆ pos_8</span></span><br><span class="line">       instanceWrapper = createBeanInstance(beanName, mbd, args);</span><br><span class="line">    &#125;</span><br><span class="line">    Object bean = instanceWrapper.getWrappedInstance();</span><br><span class="line">    Class&lt;?&gt; beanType = instanceWrapper.getWrappedClass();</span><br><span class="line">    <span class="keyword">if</span> (beanType != NullBean.class) &#123;</span><br><span class="line">       mbd.resolvedTargetType = beanType;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 提前暴露单实例。专门来解决循环引用问题；Eagerly cache singletons to be able to resolve circular references</span></span><br><span class="line">    <span class="comment">// even when triggered by lifecycle interfaces like BeanFactoryAware.  </span></span><br><span class="line">    <span class="comment">// ☆☆☆ pos_9</span></span><br><span class="line">    <span class="keyword">boolean</span> earlySingletonExposure = (mbd.isSingleton() &amp;&amp; <span class="keyword">this</span>.allowCircularReferences &amp;&amp;</span><br><span class="line">          isSingletonCurrentlyInCreation(beanName));</span><br><span class="line">    <span class="keyword">if</span> (earlySingletonExposure) &#123;</span><br><span class="line">       <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">          logger.trace(<span class="string">&quot;Eagerly caching bean &#x27;&quot;</span> + beanName +</span><br><span class="line">                <span class="string">&quot;&#x27; to allow for resolving potential circular references&quot;</span>);</span><br><span class="line">       &#125;</span><br><span class="line">       addSingletonFactory(beanName, () -&gt; getEarlyBeanReference(beanName, mbd, bean)); <span class="comment">//三级缓存中的Bean也会被后置处理来增强，</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Initialize the bean instance.</span></span><br><span class="line">    Object exposedObject = bean;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">       <span class="comment">// ☆☆☆ pos_10</span></span><br><span class="line">       populateBean(beanName, mbd, instanceWrapper); <span class="comment">//给创建好的对象每个属性进行赋值，@Autowired发生在这里</span></span><br><span class="line">       exposedObject = initializeBean(beanName, exposedObject, mbd);<span class="comment">//初始化bean</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">       <span class="keyword">if</span> (ex <span class="keyword">instanceof</span> BeanCreationException &amp;&amp; beanName.equals(((BeanCreationException) ex).getBeanName())) &#123;</span><br><span class="line">          <span class="keyword">throw</span> (BeanCreationException) ex;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">                mbd.getResourceDescription(), beanName, <span class="string">&quot;Initialization of bean failed&quot;</span>, ex);</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//早期单实例暴露</span></span><br><span class="line">    <span class="keyword">if</span> (earlySingletonExposure) &#123;</span><br><span class="line">       Object earlySingletonReference = getSingleton(beanName, <span class="keyword">false</span>); <span class="comment">//检查早期缓存中是否存在这个组件</span></span><br><span class="line">       <span class="keyword">if</span> (earlySingletonReference != <span class="keyword">null</span>) &#123;</span><br><span class="line">          <span class="keyword">if</span> (exposedObject == bean) &#123;</span><br><span class="line">             exposedObject = earlySingletonReference;</span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">else</span> <span class="keyword">if</span> (!<span class="keyword">this</span>.allowRawInjectionDespiteWrapping &amp;&amp; hasDependentBean(beanName)) &#123;</span><br><span class="line">             String[] dependentBeans = getDependentBeans(beanName);</span><br><span class="line">             Set&lt;String&gt; actualDependentBeans = <span class="keyword">new</span> LinkedHashSet&lt;&gt;(dependentBeans.length);</span><br><span class="line">             <span class="keyword">for</span> (String dependentBean : dependentBeans) &#123;</span><br><span class="line">                <span class="keyword">if</span> (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) &#123;</span><br><span class="line">                   actualDependentBeans.add(dependentBean);</span><br><span class="line">                &#125;</span><br><span class="line">             &#125;</span><br><span class="line">             <span class="keyword">if</span> (!actualDependentBeans.isEmpty()) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> BeanCurrentlyInCreationException(beanName,</span><br><span class="line">                      <span class="string">&quot;Bean with name &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27; has been injected into other beans [&quot;</span> +</span><br><span class="line">                      StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +</span><br><span class="line">                      <span class="string">&quot;] in its raw version as part of a circular reference, but has eventually been &quot;</span> +</span><br><span class="line">                      <span class="string">&quot;wrapped. This means that said other beans do not use the final version of the &quot;</span> +</span><br><span class="line">                      <span class="string">&quot;bean. This is often the result of over-eager type matching - consider using &quot;</span> +</span><br><span class="line">                      <span class="string">&quot;&#x27;getBeanNamesForType&#x27; with the &#x27;allowEagerInit&#x27; flag turned off, for example.&quot;</span>);</span><br><span class="line">             &#125;</span><br><span class="line">          &#125;</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Register bean as disposable.</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">       registerDisposableBeanIfNecessary(beanName, bean, mbd);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (BeanDefinitionValidationException ex) &#123;</span><br><span class="line">       <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">             mbd.getResourceDescription(), beanName, <span class="string">&quot;Invalid destruction signature&quot;</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> exposedObject;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>



<h2 id="流程"><a href="#流程" class="headerlink" title="流程"></a>流程</h2><ol>
<li>pos_1位置先进入pos_3位置的<code>getSingleton(beanName, true)</code>，查看缓存中有没有A组件</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009165057518.png"/>

<ol start="2">
<li>然后走到pos_2调用pos_5的<code>getSingleton()</code>开始创建A的流程</li>
<li>在pos_5的<code>getSingleton()</code>中走到pos_6的<code>beforeSingletonCreation()</code>，就变成下面这样</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009165924811.png"/>

<ol start="4">
<li><p>接着pos_7的会调用pos_2的lamda表达式里的<code>createbean()</code>，里面再调用<code>doCreateBean()</code>。前面讲过不多说，最终调用A的无参构造(pos_8)，创建完之后发现A的B属性是null。</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009170632290.png"/>

<p>5.在pos_9处的<code>addSingletonFactory()</code>来准备解决循环引用</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">addSingletonFactory</span><span class="params">(String beanName, ObjectFactory&lt;?&gt; singletonFactory)</span> </span>&#123;</span><br><span class="line">   Assert.notNull(singletonFactory, <span class="string">&quot;Singleton factory must not be null&quot;</span>);</span><br><span class="line">   <span class="keyword">synchronized</span> (<span class="keyword">this</span>.singletonObjects) &#123;</span><br><span class="line">      <span class="keyword">if</span> (!<span class="keyword">this</span>.singletonObjects.containsKey(beanName)) &#123; <span class="comment">//当前对象如果没有在单例池中</span></span><br><span class="line">         <span class="keyword">this</span>.singletonFactories.put(beanName, singletonFactory);</span><br><span class="line">         <span class="keyword">this</span>.earlySingletonObjects.remove(beanName);</span><br><span class="line">         <span class="keyword">this</span>.registeredSingletons.add(beanName);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009171641665.png"/>



<ol start="6">
<li>接着在pos_10处的<code>populateBean()</code>开始给属性赋值，这一步就是要把<code>B b</code>自动装配进来。主要是</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">populateBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> BeanWrapper bw)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (bw == <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">if</span> (mbd.hasPropertyValues()) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">               mbd.getResourceDescription(), beanName, <span class="string">&quot;Cannot apply property values to null instance&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="comment">// Skip property population phase for null instance.</span></span><br><span class="line">         <span class="keyword">return</span>;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// @Autowired赋值也在这里(但是没做事)。可以中断初始化行为； 在属性赋值之前，后置处理器可以提前准备些东西 Give any InstantiationAwareBeanPostProcessors the opportunity to modify the</span></span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (!mbd.isSynthetic() &amp;&amp; hasInstantiationAwareBeanPostProcessors()) &#123;</span><br><span class="line">      <span class="keyword">for</span> (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) &#123;</span><br><span class="line">         <span class="keyword">if</span> (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125; <span class="comment">//以上的后置处理器可以中断以下的行为</span></span><br><span class="line"></span><br><span class="line">   PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : <span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">int</span> resolvedAutowireMode = mbd.getResolvedAutowireMode();</span><br><span class="line">   <span class="keyword">if</span> (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) &#123;</span><br><span class="line">      <span class="comment">// ...</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">boolean</span> hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();</span><br><span class="line">   <span class="keyword">boolean</span> needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);</span><br><span class="line"></span><br><span class="line">   PropertyDescriptor[] filteredPds = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">if</span> (hasInstAwareBpps) &#123;</span><br><span class="line">      <span class="keyword">if</span> (pvs == <span class="keyword">null</span>) &#123;</span><br><span class="line">         pvs = mbd.getPropertyValues(); <span class="comment">//xml中property标签指定的</span></span><br><span class="line">      &#125; <span class="comment">//使用后置处理器处理属性</span></span><br><span class="line">      <span class="keyword">for</span> (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) &#123;</span><br><span class="line">         PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);</span><br><span class="line">         <span class="keyword">if</span> (pvsToUse == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (filteredPds == <span class="keyword">null</span>) &#123;</span><br><span class="line">               filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);</span><br><span class="line">            &#125;</span><br><span class="line">            pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);</span><br><span class="line">            <span class="keyword">if</span> (pvsToUse == <span class="keyword">null</span>) &#123;</span><br><span class="line">               <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         pvs = pvsToUse; <span class="comment">//封装了当前bean的所有属性名和值，可以由后置处理器处理得到</span></span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (pvs != <span class="keyword">null</span>) &#123; <span class="comment">//把以前处理好的PropertyValues给bean里面设置一下。主要是上面步骤没有给bean里面设置的属性</span></span><br><span class="line">      applyPropertyValues(beanName, mbd, bw, pvs); <span class="comment">//xml版的所有配置会来到这里给属性赋值</span></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>通过前面讲过的AutowiredAnnotationBeanPostProcessor来注入B，最后发现要调用setB方法给B赋值</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009172602037.png"/>

<ol start="7">
<li>继续走，发现要想获得B还是要调用getBean</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009172943987.png" />

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">resolveCandidate</span><span class="params">(String beanName, Class&lt;?&gt; requiredType, BeanFactory beanFactory)</span></span></span><br><span class="line"><span class="function">      <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">return</span> beanFactory.getBean(beanName); <span class="comment">//所有自动注入的属性都是beanFactory.getBean(beanName);的结果</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>然后图就是这样子</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009173310844.png"/>



<ol start="8">
<li>B也是走这一套</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009175223998.png"/>

<ol start="9">
<li>B为了获取A，还要再走一次getBean()流程，最终还是走到</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//☆☆☆ pos_4</span></span><br><span class="line"> <span class="meta">@Nullable</span>  <span class="comment">//双检查锁</span></span><br><span class="line"> <span class="function"><span class="keyword">protected</span> Object <span class="title">getSingleton</span><span class="params">(String beanName, <span class="keyword">boolean</span> allowEarlyReference)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//先检查单例缓存池，获取当前对象  Quick check for existing instance without full singleton lock</span></span><br><span class="line">    Object singletonObject = <span class="keyword">this</span>.singletonObjects.get(beanName); <span class="comment">//一级缓存</span></span><br><span class="line">    <span class="keyword">if</span> (singletonObject == <span class="keyword">null</span> &amp;&amp; isSingletonCurrentlyInCreation(beanName)) &#123; <span class="comment">//如果当前bean正在创建过程中，而且缓存中没有则继续</span></span><br><span class="line">       singletonObject = <span class="keyword">this</span>.earlySingletonObjects.get(beanName); <span class="comment">//二级</span></span><br><span class="line">       <span class="keyword">if</span> (singletonObject == <span class="keyword">null</span> &amp;&amp; allowEarlyReference) &#123;</span><br><span class="line">          <span class="keyword">synchronized</span> (<span class="keyword">this</span>.singletonObjects) &#123;</span><br><span class="line">             <span class="comment">// Consistent creation of early reference within full singleton lock</span></span><br><span class="line">             singletonObject = <span class="keyword">this</span>.singletonObjects.get(beanName);</span><br><span class="line">             <span class="keyword">if</span> (singletonObject == <span class="keyword">null</span>) &#123;</span><br><span class="line">                singletonObject = <span class="keyword">this</span>.earlySingletonObjects.get(beanName);</span><br><span class="line">                <span class="keyword">if</span> (singletonObject == <span class="keyword">null</span>) &#123;</span><br><span class="line">                   ObjectFactory&lt;?&gt; singletonFactory = <span class="keyword">this</span>.singletonFactories.get(beanName); <span class="comment">//三级</span></span><br><span class="line">                   <span class="keyword">if</span> (singletonFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">                      singletonObject = singletonFactory.getObject();<span class="comment">// 用那个lamda表达式拿对象</span></span><br><span class="line">                      <span class="keyword">this</span>.earlySingletonObjects.put(beanName, singletonObject);</span><br><span class="line">                      <span class="keyword">this</span>.singletonFactories.remove(beanName);</span><br><span class="line">                   &#125;</span><br><span class="line">                &#125;</span><br><span class="line">             &#125;</span><br><span class="line">          &#125;</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> singletonObject;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009175603012.png"/>



<ol start="10">
<li></li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009175756620.png"/>



<ol start="11">
<li><p>得到A之后，B赋值结束。B进入初始化</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">populateBean(beanName, mbd, instanceWrapper); <span class="comment">//给创建好的对象每个属性进行赋值，@Autowired发生在这里</span></span><br><span class="line">exposedObject = initializeBean(beanName, exposedObject, mbd);<span class="comment">//初始化bean</span></span><br></pre></td></tr></table></figure></li>
<li><p>B初始化完之后，回到getSingleton，把自己放到单例池里</p>
</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009180127487.png"/>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">addSingleton</span><span class="params">(String beanName, Object singletonObject)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">synchronized</span> (<span class="keyword">this</span>.singletonObjects) &#123;</span><br><span class="line">      <span class="keyword">this</span>.singletonObjects.put(beanName, singletonObject);</span><br><span class="line">      <span class="keyword">this</span>.singletonFactories.remove(beanName);</span><br><span class="line">      <span class="keyword">this</span>.earlySingletonObjects.remove(beanName);</span><br><span class="line">      <span class="keyword">this</span>.registeredSingletons.add(beanName);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009180214917.png"/>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009180410898.png"/>

<ol start="13">
<li>B全部结束之后回到A的流程，A赋值工作结束了，然后就开始A的初始化。初始化的过程中</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009180807630.png"/>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">addSingleton</span><span class="params">(String beanName, Object singletonObject)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">synchronized</span> (<span class="keyword">this</span>.singletonObjects) &#123;</span><br><span class="line">      <span class="keyword">this</span>.singletonObjects.put(beanName, singletonObject); <span class="comment">//加到一级</span></span><br><span class="line">      <span class="keyword">this</span>.singletonFactories.remove(beanName); <span class="comment">//移除三级</span></span><br><span class="line">      <span class="keyword">this</span>.earlySingletonObjects.remove(beanName); <span class="comment">//移除二级</span></span><br><span class="line">      <span class="keyword">this</span>.registeredSingletons.add(beanName);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/image-20211009180545206.png"/>







<h2 id="全部的流程图"><a href="#全部的流程图" class="headerlink" title="全部的流程图"></a>全部的流程图</h2><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_05/循环引用.jpg">

















</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/a1b8c236.html">https://imlql.cn/post/a1b8c236.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring%E6%BA%90%E7%A0%81/">Spring源码</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/598f6b0d.html"><img class="prev-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring源码系列-第6章-AOP的后置处理器和代理对象的创建</div></div></a></div><div class="next-post pull-right"><a href="/post/49f419ae.html"><img class="next-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Spring源码系列-第4章-Bean初始化流程</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/post/41fb8d9e.html" title="Spring源码系列-第2章-后置工厂处理器和Bean生命周期"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-21</div><div class="title">Spring源码系列-第2章-后置工厂处理器和Bean生命周期</div></div></a></div><div><a href="/post/49f419ae.html" title="Spring源码系列-第4章-Bean初始化流程"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-27</div><div class="title">Spring源码系列-第4章-Bean初始化流程</div></div></a></div><div><a href="/post/fb3552e0.html" title="Spring源码系列-第7章-AOP的执行流程原理和监听器原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-04-17</div><div class="title">Spring源码系列-第7章-AOP的执行流程原理和监听器原理</div></div></a></div><div><a href="/post/c8dd1418.html" title="Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-20</div><div class="title">Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理</div></div></a></div><div><a href="/post/6f2cef28.html" title="Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-21</div><div class="title">Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理</div></div></a></div><div><a href="/post/4dfb096b.html" title="Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-05</div><div class="title">Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC5%E7%AB%A0-%E5%AE%B9%E5%99%A8%E5%88%B7%E6%96%B0%E6%B5%81%E7%A8%8B"><span class="toc-text">第5章-容器刷新流程</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E5%9B%BE-%E5%AE%B9%E5%99%A8%E5%88%B7%E6%96%B0"><span class="toc-text">流程图-容器刷新</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%B9%E5%99%A8%E5%88%9B%E5%BB%BA"><span class="toc-text">容器创建</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#AnnotationConfigApplicationContext%E6%9C%89%E5%8F%82%E6%9E%84%E9%80%A0"><span class="toc-text">AnnotationConfigApplicationContext有参构造</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#AnnotationConfigApplicationContext-this-%E6%97%A0%E5%8F%82%E6%9E%84%E9%80%A0"><span class="toc-text">AnnotationConfigApplicationContext#this()无参构造</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#AnnotatedBeanDefinitionReader%E6%9C%89%E5%8F%82%E6%9E%84%E9%80%A0"><span class="toc-text">AnnotatedBeanDefinitionReader有参构造</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AnnotationConfigUtils-registerAnnotationConfigProcessors-%E6%B3%A8%E5%86%8CSpring%E5%86%85%E9%83%A8%E5%87%A0%E4%B8%AA%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6"><span class="toc-text">AnnotationConfigUtils#registerAnnotationConfigProcessors()注册Spring内部几个核心组件</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#RootBeanDefinition"><span class="toc-text">RootBeanDefinition</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractBeanDefinition"><span class="toc-text">AbstractBeanDefinition</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#ClassPathBeanDefinitionScanner"><span class="toc-text">ClassPathBeanDefinitionScanner</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AnnotationConfigApplicationContext-register"><span class="toc-text">AnnotationConfigApplicationContext#register()</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#AnnotatedBeanDefinitionReader-register-%E6%B3%A8%E5%86%8C%E4%B8%BB%E9%85%8D%E7%BD%AE%E7%B1%BBBeanDefinition"><span class="toc-text">AnnotatedBeanDefinitionReader#register()注册主配置类BeanDefinition</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AnnotationConfigUtils-processCommonDefinitionAnnotations-%E6%84%9F%E7%9F%A5-Lazy%EF%BC%8C-Primary%E7%AD%89%E6%B3%A8%E8%A7%A3"><span class="toc-text">AnnotationConfigUtils#processCommonDefinitionAnnotations()感知@Lazy，@Primary等注解</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#AbstractApplicationContext-refresh-%E5%BC%80%E5%A7%8B%E5%AE%B9%E5%99%A8%E5%88%B7%E6%96%B0"><span class="toc-text">AbstractApplicationContext#refresh()开始容器刷新</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#prepareRefresh-%E5%87%86%E5%A4%87%E4%B8%8A%E4%B8%8B%E6%96%87%E7%8E%AF%E5%A2%83"><span class="toc-text">prepareRefresh()准备上下文环境</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#initPropertySources"><span class="toc-text">initPropertySources()</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#prepareBeanFactory-%E7%BB%99BeanFactory%E5%87%86%E5%A4%87%E4%B8%80%E4%BA%9B%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6"><span class="toc-text">prepareBeanFactory()给BeanFactory准备一些核心组件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#postProcessBeanFactory-%E7%95%99%E7%BB%99%E5%AD%90%E7%B1%BB%E7%9A%84%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95"><span class="toc-text">postProcessBeanFactory()留给子类的模板方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#invokeBeanFactoryPostProcessors-%E5%B7%A5%E5%8E%82%E5%A2%9E%E5%BC%BA%E3%80%90%E6%A0%B8%E5%BF%83%E3%80%91"><span class="toc-text">invokeBeanFactoryPostProcessors()工厂增强【核心】</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#ConfigurationClassPostProcessor-postProcessBeanDefinitionRegistry-%E5%BC%80%E5%A7%8B%E8%A7%A3%E6%9E%90-Configuration%E6%A0%87%E6%B3%A8%E7%9A%84%E6%89%80%E6%9C%89%E9%85%8D%E7%BD%AE%E7%B1%BB%E7%9B%B8%E5%85%B3%E4%BF%A1%E6%81%AF%EF%BC%8C%E5%B9%B6%E7%94%9F%E6%88%90Bean"><span class="toc-text">ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry()开始解析@Configuration标注的所有配置类相关信息，并生成Bean</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ConfigurationClassParser-parse"><span class="toc-text">ConfigurationClassParser#parse()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ConfigurationClassParser-doProcessConfigurationClass-%E8%A7%A3%E6%9E%90%E9%85%8D%E7%BD%AE%E7%B1%BB%E4%B8%AD%E8%AF%B8%E5%A6%82-ComponentScan%EF%BC%8C-Import%EF%BC%8C-Bean%E7%AD%89%E6%B3%A8%E8%A7%A3"><span class="toc-text">ConfigurationClassParser#doProcessConfigurationClass()解析配置类中诸如@ComponentScan，@Import，@Bean等注解</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ComponentScanAnnotationParser-parse-%E5%85%B7%E4%BD%93%E5%A6%82%E4%BD%95%E8%A7%A3%E6%9E%90-ComponentScan%E6%B3%A8%E8%A7%A3%E3%80%82%E8%BF%99%E9%87%8C%E4%B9%9F%E6%98%AF-Component%E6%B3%A8%E8%A7%A3%E7%94%9F%E6%95%88%E7%9A%84%E5%9C%B0%E6%96%B9"><span class="toc-text">ComponentScanAnnotationParser#parse()具体如何解析@ComponentScan注解。这里也是@Component注解生效的地方</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#ClassPathBeanDefinitionScanner-doScan"><span class="toc-text">ClassPathBeanDefinitionScanner#doScan()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#ClassPathScanningCandidateComponentProvider-findCandidateComponents"><span class="toc-text">ClassPathScanningCandidateComponentProvider#findCandidateComponents()</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#registerBeanPostProcessors-%E6%B3%A8%E5%86%8C%E6%89%80%E6%9C%89%E7%9A%84Bean%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8"><span class="toc-text">registerBeanPostProcessors()注册所有的Bean后置处理器</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#PostProcessorRegistrationDelegate-registerBeanPostProcessors"><span class="toc-text">PostProcessorRegistrationDelegate#registerBeanPostProcessors()</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#initMessageSource"><span class="toc-text">initMessageSource()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#initApplicationEventMulticaster"><span class="toc-text">initApplicationEventMulticaster()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#onRefresh-%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95%E7%95%99%E7%BB%99%E5%AD%90%E7%B1%BB%E7%BB%A7%E7%BB%AD%E5%A2%9E%E5%BC%BA%E5%A4%84%E7%90%86"><span class="toc-text">onRefresh()模板方法留给子类继续增强处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#registerListeners"><span class="toc-text">registerListeners()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#finishBeanFactoryInitialization-%E6%AD%A3%E5%BC%8F%E5%88%9B%E5%BB%BA%E6%89%80%E6%9C%89%E6%99%AE%E9%80%9ABean"><span class="toc-text">finishBeanFactoryInitialization()正式创建所有普通Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#finishRefresh-%E4%B8%BB%E8%A6%81%E6%98%AF%E5%8F%91%E9%80%81%E5%AE%B9%E5%99%A8%E5%88%B7%E6%96%B0%E5%AE%8C%E6%88%90%E7%9A%84%E4%BA%8B%E4%BB%B6"><span class="toc-text">finishRefresh()主要是发送容器刷新完成的事件</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%A1%A5%E5%85%85%EF%BC%9A%E5%BE%AA%E7%8E%AF%E5%BC%95%E7%94%A8%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-text">补充：循环引用解决方案</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8B%E8%AF%95%E7%B1%BB"><span class="toc-text">测试类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#A"><span class="toc-text">A</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#B"><span class="toc-text">B</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A0%B8%E5%BF%83%E4%BB%A3%E7%A0%81"><span class="toc-text">核心代码</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractBeanFactory"><span class="toc-text">AbstractBeanFactory</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DefaultSingletonBeanRegistry"><span class="toc-text">DefaultSingletonBeanRegistry</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory"><span class="toc-text">AbstractAutowireCapableBeanFactory</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B"><span class="toc-text">流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%A8%E9%83%A8%E7%9A%84%E6%B5%81%E7%A8%8B%E5%9B%BE"><span class="toc-text">全部的流程图</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>